android 单纯的连接服务器是比较简单的,在网上一搜一大堆的资料,但是得到服务器指定方法的返回值就需要麻烦一点,我把整体的框架写下来,以备记录参考学习
第一步:新建android 项目,在默认生成的布局文件里面加上listView
<ListView android:id="@+id/ListView01" android:layout_width="wrap_content" android:layout_height="wrap_content" />
创建这个列表的详细显示的XML文件,只是显示方式而已,就不再赘述
第二步:创建连接服务器的相关类:
1.WebServicesUtil
public class WebServicesUtil { public SoapObject soapObject; private static String TAG = "MYMESSAGE"; private final static String NAMESPACE = "";//空间名 //服务端的URL地址 private static String WebUrl="http://"; //调用的服务端方法名 private static String METHODNAME; //发送给服务器的数据 private static HashMap<String, Object> PARAMS = new HashMap<String, Object>(); //服务器返回的数据 private static String RESULT; static ProgressDialog progressDialog=null; public static boolean showProgressDialog=true; public static Context CONTEXT; /** * 请求webservice * @param url 服务器地址 * @param nameSpace 命名空间 * @param methodName 方法名 * @param params 发给服务器的数据 * @return */ public static void CallWebService(String methodName,HashMap <String ,Object> params, Handler handler,Context context) { METHODNAME = methodName; PARAMS = params; CONTEXT = context; HttpThread thread = new HttpThread(handler); thread.doStart(WebUrl, NAMESPACE, methodName, params,context); //启动线程 } }
2.HttpThread类
public class HttpThread extends Thread { private Handler handle = null; String url = null; String nameSpace = null; String methodName = null; public boolean showProgressDialog = true; HashMap<String, Object> params = null; ProgressDialog progressDialog = null; // 构造函数 public HttpThread(Handler hander) { handle = hander; } /** * 启动线程 */ public void doStart(String url, String nameSpace, String methodName, HashMap<String, Object> params, Context context) { this.url = url; this.nameSpace = nameSpace; this.methodName = methodName; this.params = params; progressDialog = new ProgressDialog(context); progressDialog.setTitle("提示"); progressDialog.setMessage("正在请求请稍等......"); progressDialog.setButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { BaseInfo.context = ""; arg0.cancel(); } }); if (showProgressDialog) { progressDialog.show(); } else { progressDialog.dismiss(); } this.start(); } /** * 线程运行 */ @Override public void run() { super.run(); try { // web service请求 String result = (String) CallWebService(); System.out.println(result); // 构造消息 Message message = handle.obtainMessage(); Bundle b = new Bundle(); b.putString(KeyUtil.RESULTFROMWEBSERVICES, result); message.setData(b); handle.sendMessage(message); // 取消进度对话框 progressDialog.dismiss(); } catch (Exception ex) { ex.printStackTrace(); } } /** * 请求web service */ protected String CallWebService() { String SOAP_ACTION = nameSpace + "/" + methodName; // 创建SoapObject实例 SoapObject request = new SoapObject(nameSpace, methodName); // 生成调用web service方法的soap请求消息 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER10); // 设置.net web service // envelope.dotNet=true; // 发送请求 envelope.setOutputSoapObject(request); // 请求参数 if (params != null && !params.isEmpty()) { for (Iterator it = params.entrySet().iterator(); it.hasNext();) { Map.Entry e = (Entry) it.next(); request.addProperty(e.getKey().toString(), e.getValue() .toString()); } } // AndroidHttpTransport androidHttpTrandsport = new AndroidHttpTransport( url); String result = null; try { // web service请求 androidHttpTrandsport.call(SOAP_ACTION, envelope); // 得到返回结果 result = (String) envelope.getResponse().toString(); } catch (Exception ex) { ex.printStackTrace(); progressDialog.dismiss(); } return result; } }
第三步:在需要显示列表的Activity中添加相关代码
static String[] from = new String[]{"ImageView","name","age"}; private static int[] to = new int[]{R.id.imageView2,R.id.textView1,R.id.textView_2};
public void init() { listView = (ListView)findViewById(R.id.ListView01); pBar = (ProgressBar) this.findViewById(R.id.progressBar1); adapter = new SimpleAdapter(ListDataActivity.this, list, R.layout.list_layout_sample, from, to); listView.setAdapter(adapter); initStation(); } private void initStation() { pBar.setVisibility(View.VISIBLE); HashMap <String ,Object> params=new HashMap<String ,Object>(); params.put("param1", "admin"); WebServicesUtil.callWebservices("方法名", params, this, handler); } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); String data = msg.getData().getString(KeyUtil.RESULTFROMWEBSERVICES); // 从消息在拿出数据 try { JSONArray ja = new JSONArray(data); if(ja.length()>0) { for(int i=0;i<ja.length();i++) { JSONObject jo = (JSONObject) ja.get(i); HashMap<String,Object> map = new HashMap<String, Object>(); map.put(from[0], R.drawable.station); map.put(from[1], JSONTools.getStringfromJson(jo, "NAME", "")); map.put(from[2], JSONTools.getStringfromJson(jo, "age", "")); list.add(map); } adapter.notifyDataSetChanged(); } else { Toast.makeText(ListDataActivity.this, "没有找到!", Toast.LENGTH_LONG).show(); } } catch (Exception e) { e.printStackTrace(); Toast.makeText(ListDataActivity.this, "数据下载错误", Toast.LENGTH_LONG).show(); } pBar.setVisibility(View.GONE); } };
要特别注意的是要在功能清单文件中加*问网络的权限
<uses-permission android:name="android.permission.INTERNET"/>
附:虽然代码是经本人亲自测试,没有任何问题,但是在代码移植或是新建项目的时候会出现各种错,我也是纠结了两天才逐一解决.
注意1:这个地方一定要把包ksoap包勾选上,否则会找不到
注意二:android webservice ksoap 一不小心就会报错 org.xmlpull.v1.XmlPullParserException: expected: START_TAG
这个错的解决方法我从一个网友那里搜集过来,附上如下:
1. 在AndroidManifest.xml 中加入 访问网络的权限。
<uses-permission android:name="android.permission.INTERNET"/>
2. namespace和url 中 ip、port请尽量填写WIFI或者公网,因为如果你用手机去模拟上传,你的手机是连接不到内网的(如IP:192.168.1.1或 localhost)。
3. Webservice服务器的Soap版本为1.0,所以客户端指定
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); VER11改为VER10
4. String url = "http://134.192.44.105:8080/SSH2/service/IService?wsdl";
Url指的是你的webservice的地址.一般都是以***.wsdl或者***.?wsdl结束的...但是.需要注意的是..要去掉后面的.wsdl或者.?wsdl。