Android开发,需要连接webservice,之前就想用谷歌提供的jar包,下载地址:http://pan.baidu.com/s/1hqMTUHe
把它下载下来粘贴到libs文件夹下即可:
网上有很多类似的方法,我尝试了很多都没有成功,最后发现是我下载的jar包有问题导致我一直卡在哪儿。
首先添加网络权限:
<uses-permission android:name="android.permission.INTERNET"/>
这是全部代码,包括获取远程webservice当中数据并用ListView显示:
package com.example.webservice; import java.io.IOException;
import java.util.ArrayList;
import java.util.List; import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException; import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast; public class MainActivity extends Activity {
//命名空间
String nameSpace="http://tempuri.org/";
//调用方法
String methodName="selectStuAll";//webservice存在的方法名称
String endPoint="http://10.0.2.2:8011/WebService.asmx?wsdl";//本地测试完整的链接
String soapAction="http://tempuri.org/selectStuAll";//命名空间和调用方法名 private ListView listview;
private ListAdapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview=(ListView) findViewById(R.id.listView1); adapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,getsource());
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() { @Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO 自动生成的方法存根
Toast.makeText(MainActivity.this, ">>"+adapter.getItem(arg2),).show();
}
});
}
public List<String> getsource()
{
List<String> list=new ArrayList<String>(); //实例化SoapObject对象
SoapObject request=new SoapObject(nameSpace, methodName);
//第二步:假设方法有参数的话,设置调用方法参数
/* request.addProperty("username","1");
request.addProperty("password","2");
request.addProperty("tel","3");*/
//获得序列化的Envelope
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER12);
envelope.bodyOut=request;
envelope.dotNet=true;
HttpTransportSE transport=new HttpTransportSE(endPoint);
try {
transport.call(soapAction, envelope);
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
SoapObject result = null;
try {
result = (SoapObject)envelope.getResponse();
} catch (SoapFault e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} int count=result.getPropertyCount();
for(int index=;index<count;index=index+){
list.add(result.getProperty(index).toString());
}
return list;
}
}
这样就大功告成了,如果用到这个方法有问题,在下面评论,我会帮你解决。