Android calls WebService


Introduction to this section:

After the previous study, data request, data analysis, file upload and download, etc., we should be able to meet the basic requirements for interacting with the server. demand, and this section introduces Android to call WebService. In fact, this thing is somewhat similar to some of the methods provided to us. Data platform for raw data API services, such as aggregated data! WebService uses XML and SOAP, through HTTP protocol You can complete the interaction with the remote machine! Well, without further ado, let’s start this section~


Introduction to WebService

1.png

PS: If you read the above introduction If it's not clear yet, 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 WebService. Then parse the returned XML data, and then display the relevant data on our Android device!


2. Where to get WebService service

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

webXmlhttp://www.webxml.com.cn/zh_cn/index .aspx

It used to be free, but it has become commercialized. Many services require charges, but you can try them out~ The site provides 16 different Web services. You can query the corresponding services and call different interfaces according to your own needs!

Related pages of webXml

2.jpg

##Related usage times description:

3.jpg

云ju36wuhttp://www.36wu.com/Service

is also available There are many services, and 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 20 requests in an hour; Click to apply for use and get the key! Just choose one of the two!

4.jpg


3. Preparation of third-party jar package

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, ksoap2 Android is used, an efficient and lightweight SOAP development package!

jar package download address:

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

Tianchao may not be able to get up. Here are two links to Baidu Cloud for everyone to download:

2.54 version : ksoap2-android 2.54.jar

3.30 versionksoap2-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:

5.jpg

6.jpg


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 can be found like this:

7.jpg

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

8.png

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

9.png

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

11.png

Hey, here is the returned XML, and we want What we do is to parse such an XML. In addition, here .gif represents the weather icon!

Similarly, let’s look at SoapAction, NameSpace and related parameters mark for the ownership query!

12.png

and the returned XML data :

15.png


5. Register and Enable related WEB services

16.jpg

17.jpg

18.png

Click My Web Server, then click Trial. WebXML provides us with a five-day free trial. Let's start the two servers we need!

Okay, remember to mark our own key~


6. Code example for calling WebService

Well, let’s write the code to verify the call WebService process:

Operation renderings:

19.png

PS: This number is the previous number=-=, don’t try to call it , has been replaced~ In addition, the weather service seems to have writing problems, and sometimes it cannot be obtained. It is probably due to some limitations of WebXml. After all, try it out...

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;

    private String city;
    private String number;
    private String result;


    //定义获取手机信息的SoapAction与命名空间,作为常量
    private static final String AddressnameSpace = "http://WebXml.com.cn/";
    //天气查询相关参数
    private static final String Weatherurl = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx";
    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";


    //定义一个Handler用来更新页面:
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0x001:
                    txt_result.setText("结果显示:\n" + result);
                    Toast.makeText(MainActivity.this, "获取天气信息成功", Toast.LENGTH_SHORT).show();
                    break;
                case 0x002:
                    txt_result.setText("结果显示:\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;
        }
    }


    //定义一个获取某城市天气信息的方法:
    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("天气服务设置完毕,准备开启服务");
        try {
            httpTransportSE.call(WeathersoapAction, envelope);
//            System.out.println("调用WebService服务成功");
        } catch (Exception e) {
            e.printStackTrace();
//            System.out.println("调用WebService服务失败");
        }

        //获得服务返回的数据,并且开始解析
        SoapObject object = (SoapObject) envelope.bodyIn;
        System.out.println("获得服务数据");
        result = object.getProperty(1).toString();
        handler.sendEmptyMessage(0x001);
        System.out.println("发送完毕,textview显示天气信息");
    }


    //定义一个获取号码归属地的方法:
    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.VER11);
        envelope.bodyOut = soapObject;
        envelope.dotNet = true;
        envelope.setOutputSoapObject(soapObject);
        HttpTransportSE httpTransportSE = new HttpTransportSE(Addressurl);
        //	System.out.println("号码信息设置完毕,准备开启服务");
        try {
            httpTransportSE.call(AddresssoapAction, envelope);
            //System.out.println("调用WebService服务成功");
        } catch (Exception e) {
            e.printStackTrace();
            //System.out.println("调用WebService服务失败");
        }

        //获得服务返回的数据,并且开始解析
        SoapObject object = (SoapObject) envelope.bodyIn;//System.out.println("获得服务数据");
        result = object.getProperty(0).toString();//System.out.println("获取信息完毕,向主线程发信息");
        handler.sendEmptyMessage(0x001);
        //System.out.println("发送完毕,textview显示天气信息");
    }


}

In addition, don’t forget to import the package and Internet permissions!


Reference code download:

WebServiceDemo.zipDownload WebServiceDemo.zip


This section Summary:

Okay, this section explains how to use this WebService on the Android side. Let’s learn one in the next section. An Android control similar to a browser - WebView, so stay tuned~Thank you~!