Android中调用webservice小结

来源:互联网 发布:马云怎么靠淘宝挣钱 编辑:程序博客网 时间:2024/04/30 10:04
  在Android中,调用websevice的方法是使用ksoap2android这个开源库,调用的方法
其实很简单,下面例子说明之:

KSOAP2可以到http://github.com/mosabua/ksoap2-android/tree/去下载
并把它加到Android项目中的库路径中,然后代码如下
mport org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Main extends Activity {

private static String SOAP_ACTION = "http://tempuri.org/HelloWorld";

private static String NAMESPACE = "http://tempuri.org/";
private static String METHOD_NAME = "HelloWorld";

//要调用的webservice的地址
private static String URL = "http://bimbim.in/Sample/TestService.asmx?WSDL";


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
       //初始化SOAP对象
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);       
        //调用的参数
        request.addProperty("Parameter","Value");
       
       
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.setOutputSoapObject(request);
    
        //调用SOAP
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
        try {
       
      androidHttpTransport.call(SOAP_ACTION, envelope);       
        } catch (Exception e) {
        e.printStackTrace();
        }
       
// 获得SOAP调用的结果
SoapObject result = (SoapObject)envelope.bodyIn;

if(result != null){
TextView t = (TextView)this.findViewById(R.id.resultbox);
t.setText("SOAP response:\n\n" + result.getProperty(0).toString());
}

    }

记得要设置好访问INTERNET的权限:
<uses-permission android:name="android.permission.INTERNET" />