Android中調用Web Services
Android中調用Web Services有很多方法,我們現在使用的是ksoap,它是SOAP web services的客戶端包,ksoap現在版本為2.0.它的一個主要優點就是對dotNET兼容性比較不錯。
首先下載ksoap的包文件,在Eclispe的Package Explorer中右鍵項目,Build Path>Add Libraries,找到ksoap2-android-assembly-2.4-jar-with-dependencies.jar添加該引用。代碼如下:
public class WSHelper { final static String WSUrl="http://xxx/WSUrl.asmx"; private static String namespace = "http://tempuri.org/"; /************************************* * 獲取web services內容 * @param url * @param params * @return *************************************/ public static String GetResponse(String method,List<BasicNameValuePair> params){ try { String url = WSUrl; SoapObject request = new SoapObject(namespace, method); for(int i=0,len=params.size();i<len;i++){ request.addProperty(params.get(i).getName(), params.get(i).getValue()); } SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(url); androidHttpTransport.call(namespace + method, envelope); SoapPrimitive result = (SoapPrimitive)envelope.getResponse(); return result.toString(); } catch (Exception e) { return "Error:calling the web services error"; } } }調用時代碼如下:
String method = "MethodName";//方法名稱 List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(); params.add(new BasicNameValuePair("userId", String.valueOf(1995))); return WSHelper.GetResponse(method,params);
這里參數可以定義多個,返回時是以String類似來返回。
注意由于我們調用Web sevices,就需要程序有訪問網絡的權限,因此需要在AndroidManifest.xml中manifest節中增加訪問網絡權限的定義:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>文章出處: http://www.cnblogs.com/walkingp/archive/2011/04/05/2006193.html
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!