Android連接遠程資料庫,目前看來最好的解決辦法就是webservice,利用webservice進行通訊就要soap協議,目前android沒有內建相關的函數,需要藉助第三方ksoap2-android進行操作。 ...
soap2-android
官網地址
https://simpligility.github.io/ksoap2-android/index.html
發行版本
https://oss.sonatype.org/content/repositories/ksoap2-android-releases/
- 切記所需要的文件是在
com>google>code>ksoap2-android>ksoap2-android-assembly
- 選擇最新版本,然後使用-with-dependencies.jar包
最新版本
調用WebService取得數據
初使化soap
private final String serviceNameSapce = "http://192.168.20.135:8090/";
private final String serviceUrl = "http://192.168.20.135:8090/TestService.asmx";
private final String serviceMethod = "HelloWorld";
private final String serviceAction = "http://192.168.20.135:8090/HelloWorld";
private String strResult = "";
調用
new Thread(new Runnable() {
@Override
public void run() {
//創建HttpTransportSE傳輸對象,serviceUrl是webservice提供服務的url
HttpTransportSE httpTransportSE = new HttpTransportSE(serviceUrl);
//使用SOAP1.1協議創建Envelop對象,根據服務端WebService的版本號設置SOAP協議的版本號
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
//實例化SoapObject對象,第一個參數表示命名空間,第二個參數表示要調用的WebService方法名
SoapObject soapObject= new SoapObject(serviceNameSapce, serviceMethod);
//設置調用方法的參數值,如果沒有參數,可以省略
//soapObject.addProperty("theCityCode", cityName);
envelope.bodyOut = soapObject;
envelope.dotNet = true;
try {
//調用webservice
httpTransportSE.call(serviceAction, envelope);
//獲取伺服器響應返回的SOAP消息
if(envelope.getResponse() != null){
SoapObject resultSoap = (SoapObject)envelope.bodyIn;
strResult = resultSoap.getProperty(0).toString();
mHandler.sendEmptyMessage(0x002);
}
} catch (IOException | XmlPullParserException e) {
e.printStackTrace();
}
}
}).start();