Android uses an http request to query the mobile phone number of the specified location and android phone number

Source: Internet
Author: User

Android uses an http request to query the mobile phone number of the specified location and android phone number

Local Data Source

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

Webxml websites also support other request methods, such as SOAP.

Simple Interface

<? 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 = "mobile phone number: "/> <EditText android: id =" @ + id/phone_sec "android: layout_width =" fill_parent "android: layout_height =" wrap_content "android: inputType =" textPhonetic "android: singleLine = "true" android: hint = "Enter at least the first seven digits"/> <Button android: id = "@ + id/query_btn" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_gravity = "right" android: text = "query"/> <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

Below is 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;

/ **
 * Query mobile phone number attribution
 * /
public class MainActivity extends Activity {
    
    private EditText phoneSecEditText;
    private TextView resultView;
    private Button queryButton;
    private ProgressDialog proDialog;
    private Thread thread;
    
    // define message
    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("Query attribution ");
        proDialog.setMessage ("Inquiring, please be patient ...");
        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 ("The format of the number you entered is incorrect");
                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) {
            // Get phone number
            phoneSec = phoneSecEditText.getText (). toString (). trim ();
            if ("". equals (phoneSec) || phoneSec.length () <7) {
                // Send message The TextView showing the query result is cleared
                handler.sendEmptyMessage (NUMBER_FORMAT_ERROR);
                // Lock focus
                phoneSecEditText.requestFocus ();
                return;
            }
            // Query mobile phone number (segment) information
            // getRemoteInfo (phoneSec);
            thread = new Thread (new QueryThread ());
            thread.start ();
            proDialog.onStart ();
            proDialog.show ();
        }
    }
    
    class QueryThread implements Runnable {

        @Override
        public void run () {
            getRemoteInfo (phoneSec);
        }
    }
    
     / **
     * Inquiry of where the mobile phone number belongs
     * @param phoneSec phone number segment
     * /
    private void getRemoteInfo (String phoneSec) {
        // TODO Auto-generated method stub
        // Define the URL to be requested
        String requestUrl = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";
        // Create HttpClient instance
        HttpClient client = new DefaultHttpClient ();
        // Create HttpPost instance based on URL
        HttpPost post = new HttpPost (requestUrl);
        List <NameValuePair> params = new ArrayList <NameValuePair> ();
        // Set the parameters to be passed
        params.add (new BasicNameValuePair ("mobileCode", phoneSec));
        params.add (new BasicNameValuePair ("userId", ""));
        try {
            // Set URL encoding
            post.setEntity (new UrlEncodedFormEntity (params, HTTP.UTF_8));
            // Send request and get feedback
            HttpResponse response = client.execute (post);

            // Determine whether the request was successfully processed
            if (response.getStatusLine (). getStatusCode () == HttpStatus.SC_OK) {
                // Parse the returned content
                String result = EntityUtils.toString (response.getEntity ());
                // Display the query result in TextView after parsing
                //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 ();
        }
    }
    / **
     * Use regular expressions to filter HTML tags
     *
     * @param source content to be filtered
     * @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;
     }

}

 

 

Remember to configure <uses-permission android: name = "android. permission. INTERNET"/> In AndroidManifest. xml

Grant the program the permission to access the network.

Use a sub-thread to access the network to query data, and handler performs message processing.

The above explains only the most basic functions of HttpClient (initiate a POST request); most of the operations we perform on the browser client can be simulated by HttpClient, for example: submits forms, queries data, uploads and downloads documents, jumps to pages, and stores sessions.

 

GetMobileCodeInfo

Obtain information about the province, region, and mobile phone card type of the mobile phone number in mainland China.

Input parameter: mobileCode = string (mobile phone number, minimum number of the first seven digits), userID = string (commercial user ID) free user is a null string; return data: string (mobile phone number: province city mobile phone card type ).

 

 

Test results:


 


 

Reference: http://blog.csdn.net/lyq8479/article/details/6413216


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.