Android中如何調(diào)用Web Services
??Android中調(diào)用Web Services有很多方法,我們現(xiàn)在使用的是ksoap,它是SOAP web services的客戶端包,ksoap現(xiàn)在版本為2.0.它的一個(gè)主要優(yōu)點(diǎn)就是對(duì)dotNET兼容性比較不錯(cuò)。
首先下載ksoap的包文件,在Eclispe的Package Explorer中右鍵項(xiàng)目,Build Path>Add Libraries,找到ksoap2-android-assembly-2.4-jar-with-dependencies.jar添加該引用。代碼如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33public
class
WSHelper {
????
final
static
String WSUrl=
"http://xxx/WSUrl.asmx"
;
?
?????
private
static
String namespace =
"http://tempuri.org/"
;
????
/*************************************
?????
* 獲取web services內(nèi)容
?????
* @param url
?????
* @param params
?????
* @return
?????
*************************************/
????
public
static
String GetResponse(String method,List
?????????
?????????
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"
;
????????
}
????
}
}
調(diào)用時(shí)代碼如下:
?
1
2
3
4String method =
"MethodName"
;
//方法名稱(chēng)
List
new
ArrayList
params.add(
new
BasicNameValuePair(
"userId"
, String.valueOf(
1995
)));
return
WSHelper.GetResponse(method,params);
這里參數(shù)可以定義多個(gè),返回時(shí)是以String類(lèi)似來(lái)返回。
注意由于我們調(diào)用Web sevices,就需要程序有訪問(wèn)網(wǎng)絡(luò)的權(quán)限,因此需要在AndroidManifest.xml中manifest節(jié)中增加訪問(wèn)網(wǎng)絡(luò)權(quán)限的定義。