Use Android Ksoap2 to call WebService in Android

Author: Jerry Education
Source
The copyright of this article is shared by Yantai Jerry Education Technology Co., Ltd. and Blog Park. Reprinting is welcome, but this statement must be retained without the author's consent, and the original text link must be given in a prominent position on the article page, otherwise the right to pursue legal responsibility is reserved.

Use Android Ksoap2 to call WebService in Android

1. Introduction to WebService

WebService is based on the SOAP protocol, which can realize the communication between web servers and web servers. Because the use of SOAP protocol to transmit XML data is platform-independent, it is also an important solution to solve the communication between heterogeneous platforms, such as between the Java platform and the .net platform. Therefore, it plays a pivotal role in web applications. Many institutions and organizations have released WebServices (such as weather forecasts, flight information, stock market quotes, etc.) on their respective platforms, so that any platform and customers can enjoy these services. Of course, some of them have to be paid.

2. Android ksoap2 component

There are two ways to call WebService on the Android side. One is to write the code by yourself to establish a connection with the webservice, mainly through the URL to obtain the HttpUrlConnection, and then perform I/O read and write transmission and obtain data, and perform XML parsing on the obtained data, which is more troublesome. The other is to use third-party components, the more commonly used one is ksoap2-android.

The open source component ksoap2-android provides a lightweight and efficient SOAP class library for the Android platform, which can facilitate the communication between the Android side and the WebService

1.
  The address of the environment to build the ksoap2-android project: http://code.google.com/p/ksoap2-android/ You can download the latest version jar, and then add the jar to the project.

I use ksoap2-android-assembly-2.5.4-jar-with-dependencies.jar here

2. Main steps used by Ksoap2
1) Preparation of web service parameters

// webservice服务地址

String url= “http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx”;

//web服务的命名空间

String namespace=” http://WebXml.com.cn/;

//请求服务的方法名称

String methodName=”getMobileCodeInfo”;

//soap请求地址

String soapActionAddress = "http://WebXml.com.cn/getMobileCodeInfo";

Copy code
2) Create HttpTransportSE, which can send requests

HttpTransportSE transport = new HttpTransportSE(url);

3) Create SoapObject, add the data to be transmitted (information carrier)

SoapObject soapObject = new SoapObject(namespace,methodName);

soapObject.addProperty(name,value);//添加数据

...
4) Create a SoapSerializationEnvelope object, specify the xml version, and the body in the request

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

envelope.bodyOut = soapObject;

envelope.setOutputSoapObject(soapObject);

5) Send a request and call the method in webserivce

httpTransportSE.call(soapActionAddress, envelope);//服务传回的信息,会放在envelope的bodyIn属性中httpTransportSE.call(soapActionAddress, envelope);//服务传回的信息,会放在envelope的bodyIn属性中
  1. Get the data returned by the service
SoapObject object = (SoapObject) envelope.bodyIn;

3. Realization case - query the location of the mobile phone number by calling webservice

The execution effect is as follows:

Complete code implementation:

public class MainActivity extends Activity {
    
    
    ///手机归属地Webservice的参数信息
    private static final String nameSpaceAddress = "http://WebXml.com.cn/";
private static final String urlAddress
 = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";
    private static final String methodNameAddress = "getMobileCodeInfo";
    private static final String soapActionAddress = "http://WebXml.com.cn/getMobileCodeInfo";
    private TextView telAddress = null;
    private EditText tel = null;
    private Button btnAddress = null;
protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnAddress = (Button) this.findViewById(R.id.btnSearchAddress);
        telAddress = (TextView) this.findViewById(R.id.telAddress);
        tel = (EditText) this.findViewById(R.id.telNo);
        btnAddress.setOnClickListener(new Button.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                new Thread(new Runnable() {
    
    
                    public void run() {
    
    
                        getTelAddress();
                    }
                }).start();

            }
        });
/**
* 请求WebService并获得返回的手机号码归属地信息
*/
public void getTelAddress() {
    
    
        SoapObject soapObject = new 
SoapObject(nameSpaceAddress, methodNameAddress);//创建SOAP对象
        //设置属性,这些属性值通过SOAP协议传送给服务器
        soapObject.addProperty("mobileCode", tel.getText().toString());//要查询的电话号码
        soapObject.addProperty("userId", "");        
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.bodyOut = soapObject;
        envelope.dotNet = true;        
        envelope.setOutputSoapObject(soapObject);
        HttpTransportSE httpTransportSE = new HttpTransportSE(urlAddress);
        try {
    
    
            //调用服务
            httpTransportSE.call(soapActionAddress, envelope);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        //获取服务传回的数据,手机归属地信息
        SoapObject object = (SoapObject) envelope.bodyIn;
        txtAddress = object.getProperty(0).toString();
        //向主线程发送消息成功,getTelAddress函数执行完毕
        handlerAddress.sendEmptyMessage(0);
    
    }
    Handler handlerAddress = new Handler() {
    
    
        public void handleMessage(Message msg) {
    
    
            telAddress.setText(txtAddress);
            Toast.makeText(MainActivity.this, 
"获取号码归属地成功"+txtAddress, Toast.LENGTH_LONG).show();
        }
    };
}

4. Attachment: common WebService service URL

Mobile phone attribution service

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

Weather forecast web service, the data comes from the China Meteorological Administration

http://www.webxml.com.cn/WebServices/WeatherWebService.asmx

IP address to:

http://www.webxml.com.cn/WebServices/IpAddressSearchWebService.asmx

Chinese <-> English two-way translation WEB service:

http://www.webxml.com.cn/WebServices/TranslatorWebService.asmx

Train timetable

http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx

Flight inquiry service

http://webservice.webxml.com.cn/webservices/DomesticAirline.asmx

China stock market data WEB service

http://www.webxml.com.cn/WebServices/ChinaStockWebService.asmx

Chinese TV Program Preview

http://www.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx

Guess you like

Origin blog.csdn.net/LiuxXn/article/details/103178475