Android本身是不提供soap訪問webservice的功能,引用了ksoap2-android的jar實現了訪問webservice的方法。代碼如下:
static final int ACTIVITY_REQUEST_CODE_A = 100;
String TAG = "Response";
Object resultRequestSOAP = null;
static UZModuleContext moduleContext;
private static UZModuleContext mJsCallback;
//設置命名空間、訪問地址、方法名? ??
String SOAP_ACTION;? ??
String METHOD_NAME;? ??
String NAMESPACE;? ??
String URL;
String Propert;
public carapi(UZWebView webView) {
super(webView);
}
@SuppressWarnings("unused")
@UzJavascriptMethodpublic void jsmethod_QueryPassport(final UZModuleContext moduleContext){
this.moduleContext = moduleContext;
SOAP_ACTION = moduleContext.optString("SOAP_ACTION");
METHOD_NAME = moduleContext.optString("METHOD_NAME");
NAMESPACE = moduleContext.optString("NAMESPACE");
URL = moduleContext.optString("URL");
Propert = moduleContext.optString("Propert");
if("".equals(SOAP_ACTION) || "".equals(METHOD_NAME) || "".equals(NAMESPACE) || "".equals(URL) || "".equals(Propert)){
try {
? ? JSONObject ret = new JSONObject();
? ? ret.put("data", "400");
? ? moduleContext.success(ret, true);
? ? } catch (JSONException e) {
? ? e.printStackTrace();
? ? }
}else{
//異步任務執行Webservice請求? ? ?
?AsyncCallWS task = new AsyncCallWS();? ??
? task.execute();
}
}?
private class AsyncCallWS extends AsyncTask{
@Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
}
@Override
protected Void doInBackground(Void... params) {
Log.i(TAG, "doInBackground");
calculate();
return null;
}
@Override
protected void onPostExecute(Void result) {
Log.i(TAG, "onPostExecute");
}
}
public void calculate() {
try {
// ? ? ? ? ? ? 創建soapObject,即拼裝soap bodyin
try{
JSONObject propertobj = new JSONObject(Propert);
Iterator it = propertobj.keys();
while(it.hasNext()){//遍歷JSONObject
String keyname = it.next().toString();
String keyvalue = propertobj.getString(keyname);
Request.addProperty(keyname,keyvalue);
}
}catch(JSONException e){
System.out.println(e.toString());
}
// ? ? ? ? ? ? 創建soap 數據
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);
soapEnvelope.dotNet = true;
soapEnvelope.setOutputSoapObject(Request);
HttpTransportSE transport = new HttpTransportSE(URL);
// ? ? ? ? ? soap 協議發送
transport.call(SOAP_ACTION, soapEnvelope);
// ? ? ? ? ? ? soap 請求完成后返回數據并轉換成字符串
resultRequestSOAP = (Object) soapEnvelope.getResponse();
Log.i(TAG, "Result: " + resultRequestSOAP);
try {
JSONObject ret = new JSONObject();
ret.put("data", resultRequestSOAP);
moduleContext.success(ret, true);
} catch (JSONException e) {
e.printStackTrace();
}
} catch (Exception ex) {
Log.e(TAG, "Error: " + ex.getMessage());
}
}