Android calls WebService

Introduction to this section:

After the previous study, data request, data analysis, file upload and download, etc., should meet the basic needs of everyone interacting with the server. In this section, the Android call WebService introduced to you is actually a bit similar to some that provide us with raw data. A data platform for API services, such as aggregated data! The WebService uses XML and SOAP, and the interaction with the remote machine can be completed through the HTTP protocol! Well, without further ado, let’s start this section~


1. Introduction to Web Services

PS: If you are still not very clear after reading the above introduction, then forget it, the company used C# to build a WebService before! In this section, we do not discuss how to build a WebService, we only know how to obtain the services provided by the WebService, then parse the returned XML data, and then display the relevant data on our Android devices!


2. Where to get the WebService service

There are many sites that provide WebService on the Internet, first find these sites, and then obtain the corresponding services! Here we choose WebXml and Yunju 36wu as examples to explain to you, their official website:

webXml : WebXml | WEB Services | WEB Service Solutions and Technical Support | Website Design |

It used to be free, but it’s all commercialized, and many services have to be charged, but you can try it~ The site provides 16 different web services, and you can query the corresponding services and call different interfaces according to your needs!

Related pages for webXml :

Relevant usage instructions :

Yunju 36wu : Macau New Grape Entertainment 9455-Official Website Welcome

It also provides a lot of services. Many mobile apps use the interface here, such as Rainbow Bus, mobile weather, etc. However, this is also charged =-=, you can try it out, but you can only send it 20 times within an hour Request; Click Apply to use, and get the key! Just choose one of the two!


3. Preparation of third-party jar packages

First of all, if you want to call WebService on the Android platform, you need to rely on a third-party class library: ksoap2 On the Android platform, you use ksoap2 Android, an efficient and lightweight SOAP development kit!

jar package download address: https://code.google.com/p/ksoap2-android/wiki/HowToUse?tm=2

Tianchao may not be able to go up, here are two links to Baidu Cloud for you to download and use:

Version 2.54 : ksoap2-android 2.54.jar

Version 3.30 : ksoap2-android 3.30.jar

If you are lucky enough to enter the download address of the jar package, then you will see the following interface:


4. Get some related parameters

First find the service we need to obtain, and then record the relevant parameters:  NameSpace (namespace), SoapAction and URL needless to say, other parameters are found like this:

For example, what we are looking for here is the query parameter of the weather. Clicking in, we can see such a parameter document:

For example, what we need here is the function of the weather query part:

Copy the framed SoapAction and NameSpace first! Of course, we can test on this page. In addition, we are free users. You can skip the id without filling it in. After entering it, click the call button to open such a page:

Hey, here is the returned XML, and what we have to do is to parse such an XML, and the .gif here represents the weather icon!

In the same way, let's look at SoapAction, NameSpace and related parameters for the attribution query!

And the returned XML data :


5. Register and enable related WEB services

Click My Web Server, and then click Trial, WebXML provides us with a five-day free trial, we open the two servers we need!

Ok, remember to mark our own key~


6. Code example for calling WebService

Well, let's write code to verify the process of calling WebService:

Running effect diagram :

PS: This number is the previous number =-=, don't try to dial, it has already been replaced~ In addition, the weather service seems to have a writing problem, and sometimes it cannot be obtained. It is probably some restrictions made by WebXml. After all, it is a trial...

Implementation code :

public class MainActivity extends AppCompatActivity implements View.OnClickListener { 

    private EditText edit_param; 
    private Button btn_attribution ; 
    private 
    Button btn_weather 
    ; private TextView txt_result 
    ; 
    result; 
    //Define the SoapAction and namespace for obtaining mobile phone information, As a constant 
    private static final String AddressnameSpace = "http://WebXml.com.cn/"; 
    //Weather query related parameters 
    private static final String Weatherurl = "http://webservice.webxml.com.cn/WebServices/WeatherWS. asmx"; 
    //Relevant parameters for attribute query


 
    private static final String Weathermethod = "getWeather";
    private static final String WeathersoapAction = "http://WebXml.com.cn/getWeather"; 
    private static final String Addressurl = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx"; 
    private static final String Addressmethod = "getMobileCodeInfo"; 
    private static final String AddresssoapAction = "http://WebXml.com.cn/getMobileCodeInfo"; 


    //Define a Handler to update the page: 
    private Handler handler = new Handler() { 
        public void handleMessage(Message msg) { 
            switch (msg.what) { 
                case 0x001: 
                    txt_result.setText("Result display:\n" + result); 
                    Toast.makeText(MainActivity.this, "Get weather information successfully", Toast.LENGTH_SHORT).show(); 
                    break; 
                case 0x002: 
                    txt_result.setText("Result display:\n" + result);
                    Toast.makeText(MainActivity.this, "号码归属地查询成功", Toast.LENGTH_SHORT).show();
                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bindViews();
    }

    private void bindViews() {
        edit_param = (EditText) findViewById(R.id.edit_param);
        btn_attribution = (Button) findViewById(R.id.btn_attribution);
        btn_weather = (Button) findViewById(R.id.btn_weather);
        txt_result = (TextView) findViewById(R.id.txt_result);
        btn_attribution.setOnClickListener(this);
        btn_weather.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_weather:
                new Thread() {
                    @Override
                    public void run() {
                        getWether();
                    }
                }.start();
                break;
            case R.id.btn_attribution:
                new Thread(new Runnable() {
                    public void run() {
                        getland(); 
                    }
                }).start();
                break; 
        } 
    } 


    //Define a method to obtain weather information of a certain city: 
    public void getWether() { 
        result = ""; 
        SoapObject soapObject = new SoapObject(AddressnameSpace, Weathermethod); 
        soapObject.addProperty("theCityCode:" , edit_param.getText().toString()); 
        soapObject.addProperty("theUserID", "dbdf1580476240458784992289892b87"); 
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
        envelope.bodyOut = soapObject; envelope. 
        dotNet = true; 
        envelope. setOutputSoapObject(soapObject);
        HttpTransportSE httpTransportSE = new HttpTransportSE(Weatherurl);  
        System.out.println("The weather service is set up,Ready to start the service"); 
        try {
            httpTransportSE.call(WeathersoapAction, envelope); 
// System.out.println("Call WebService service successfully"); 
        } catch (Exception e) { 
            e.printStackTrace(); 
// System .out.println("Failed to call WebService service"); 
        } 

        //Get the data returned by the service, and start parsing 
        SoapObject object = (SoapObject) envelope.bodyIn; 
        System.out.println("Get service data"); 
        result = object.getProperty(1).toString(); 
        handler.sendEmptyMessage(0x001); 
        System.out.println("Send completed,textview displays weather information"); 
    } 


    //Define a method to get the location of the number: 
    public void getland() { 
        result = ""; 
        SoapObject soapObject = new SoapObject(AddressnameSpace, Addressmethod);
        soapObject.addProperty("mobileCode", edit_param.getText().toString()); 
        soapObject.addProperty("userid", "dbdf1580476240458784992289892b87"); 
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.V ER11); 
        envelope. bodyOut = soapObject; 
        envelope .dotNet = true; 
        envelope.setOutputSoapObject(soapObject); 
        HttpTransportSE httpTransportSE = new HttpTransportSE(Addressurl); 
        // System.out.println("The number information is set, ready to start the service"); 
        try { 
            httpTransportSE.call(AddresssoapAction, envelope ); 
            //System.out.println("Call WebService service successfully"); 
        } catch (Exception e) {
            e.printStackTrace(); 
            //System.out.println("Failed to call WebService service"); 
        } 

        //Get the data returned by the service, and start parsing 
        SoapObject object = (SoapObject) envelope.bodyIn;//System.out. println("Obtain service data"); 
        result = object.getProperty(0).toString();//System.out.println("After obtaining information, send a message to the main thread"); 
        handler.sendEmptyMessage(0x001); 
        //System.out.println("Send completed, textview displays weather information"); 
    } 


}

Also, don't forget about import package and Internet permissions!

<uses-permission android:name="android.permission.INTERNET"/>

Guess you like

Origin blog.csdn.net/leyang0910/article/details/131480336