android 使用http請求查詢手機號碼歸屬地,android手機號碼

來源:互聯網
上載者:User

android 使用http請求查詢手機號碼歸屬地,android手機號碼

歸屬地資料來源

http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx

webxml網站還支援其他請求方式 如SOAP等等

介面比較簡單

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingTop="5dip" android:paddingLeft="5dip" android:paddingRight="5dip" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="手機號碼:" /> <EditText android:id="@+id/phone_sec" android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="textPhonetic" android:singleLine="true" android:hint="至少輸入前七位" /> <Button android:id="@+id/query_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" android:text="查詢" /> <TextView android:id="@+id/result_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal|center_vertical" /></LinearLayout>View Code

下面是MainActivity.java


package com.sphere.guishudi;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;import android.app.Activity;import android.app.ProgressDialog;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;/** * 手機號碼歸屬地查詢  */public class MainActivity extends Activity {        private EditText phoneSecEditText;      private TextView resultView;      private Button queryButton;    private ProgressDialog proDialog;    private Thread thread;        //定義訊息    private static final int NUMBER_FORMAT_ERROR = 0;    private static final int QUERY_SUCCESS_MSG = 1;        @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        phoneSecEditText = (EditText) findViewById(R.id.phone_sec);          resultView = (TextView) findViewById(R.id.result_text);          queryButton = (Button) findViewById(R.id.query_btn);        proDialog = new ProgressDialog(MainActivity.this);        //proDialog.setTitle("查詢歸屬地");        proDialog.setMessage("正在查詢,請您耐心等待...");        queryButton.setOnClickListener(new QueryOnClickListener());    }        Handler handler = new Handler(){        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);            switch (msg.what) {            case NUMBER_FORMAT_ERROR:                phoneSecEditText.setText("");                resultView.setText("您輸入的號碼格式有誤");                break;            case QUERY_SUCCESS_MSG:                resultView.setText(msg.obj.toString());                proDialog.dismiss();                break;            default:                break;            }        }            };        String phoneSec;    class QueryOnClickListener implements OnClickListener{        @Override        public void onClick(View arg0) {            //得到手機號            phoneSec = phoneSecEditText.getText().toString().trim();            if("".equals(phoneSec)||phoneSec.length()<7){                //發送訊息 顯示查詢結果的TextView清空                  handler.sendEmptyMessage(NUMBER_FORMAT_ERROR);                //鎖定焦點                phoneSecEditText.requestFocus();                return;            }            // 查詢手機號碼(段)資訊              //getRemoteInfo(phoneSec);            thread = new Thread(new QueryThread());            thread.start();            proDialog.onStart();            proDialog.show();        }    }        class QueryThread implements Runnable{        @Override        public void run() {            getRemoteInfo(phoneSec);        }    }         /**      * 手機號段歸屬地查詢      * @param phoneSec 手機號段      */      private void getRemoteInfo(String phoneSec) {        // TODO Auto-generated method stub        // 定義待請求的URL        String requestUrl = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";        // 建立HttpClient執行個體        HttpClient client = new DefaultHttpClient();        // 根據URL建立HttpPost執行個體        HttpPost post = new HttpPost(requestUrl);        List<NameValuePair> params = new ArrayList<NameValuePair>();        // 設定需要傳遞的參數        params.add(new BasicNameValuePair("mobileCode", phoneSec));        params.add(new BasicNameValuePair("userId", ""));        try {            // 設定URL編碼            post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));            // 發送請求並擷取反饋            HttpResponse response = client.execute(post);            // 判斷請求是否成功處理            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {                // 解析返回的內容                String result = EntityUtils.toString(response.getEntity());                // 將查詢結果經過解析後顯示在TextView中                //resultView.setText(filterHtml(result));                Message msg = new Message();                msg.what = QUERY_SUCCESS_MSG;                msg.obj = filterHtml(result);                handler.sendMessage(msg);            }        } catch (Exception e) {            e.printStackTrace();        }    }    /**      * 使用Regex過濾HTML標記      *       * @param source 待過濾內容      * @return      */      private String filterHtml(String source) {          if(null == source){              return "";          }          return source.replaceAll("</?[^>]+>","").trim();      }          @Override    public boolean onCreateOptionsMenu(Menu menu) {        getMenuInflater().inflate(R.menu.main, menu);        return true;    }}

 

 

記得在AndroidManifest.xml中配置<uses-permission android:name="android.permission.INTERNET" />

給予程式訪問網路的許可權。

使用子線程訪問網路查詢資料,handler做訊息處理。

上面所講解的只是HttpClient最基本的功能(發起POST請求);我們在瀏覽器用戶端所執行的大多數操作HttpClient都能夠類比,例如:提交表單、查詢資料、上傳下載文檔、頁面跳轉、Session儲存等。

 

getMobileCodeInfo 

獲得國內手機號碼歸屬地省份、地區和手機卡類型資訊

輸入參數:mobileCode = 字串(手機號碼,最少前7位元字),userID = 字串(商業使用者ID) 免費使用者為空白字串;返回資料:字串(手機號碼:省份 城市 手機卡類型)。

 

 

測試結果:如下

 

 

參考:http://blog.csdn.net/lyq8479/article/details/6413216

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.