AndroidでSOAPを使用してwebserviceとデータインタラクションを行う
3813 ワード
プロジェクトではSOAPを使用してサーバとデータのインタラクションを行う必要があるため、SOAPとWebService間の通信を熟知するための非常に簡単な例を示した.
まず、プロジェクトにKSOAPのandroidバージョンに基づくjarパッケージksoap 2-android-assembly-2.5を導入する必要がある.4-jar-with-dependencies.jar
Androidでのコード実装:
//1, WebService xxxx.com
String nameSpace = "http://www.xxxx.com/";
//2,
String methodName = "HelloWorld";
//3, EndPoint
String endPoint = "http://www.xxxx.com/helloworld.asmx";
//4, SOAPAction
// SOAP Action +
String soapAction = "http://www.xxxx.com/HelloWorld";
// WebService
SoapObject rpc = new SoapObject(nameSpace, methodName);
// , WebService
// HelloWorld
// rpc.addProperty(" ", );
// WebService SOAP , SOAP
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
// dotNet WebService
// envelope.dotNet = true;
//
envelope.bodyOut = rpc;
envelope.setOutputSoapObject(rpc);
HttpTransportSE transport = new HttpTransportSE(endPoint);
try {
// WebService
transport.call(soapAction, envelope);
} catch (Exception e) {
e.printStackTrace();
}
//
SoapObject object = (SoapObject) envelope.bodyIn;
// getMobileCodeInfoResult
String result = object.getProperty("HelloWorldResult").toString();
// WebService TextView
resultView.setText(result);
endPointつまりリクエストurlの後に付けますか?wsdlがブラウザでこのアドレスにアクセスすると、以下のフォーマットのxmlが表示されます.
-
-
- //WebService
- //
- // HelloWorldResponse HelloWorld
-
-
SOAPエラー:java.lang.RuntimeException: Cannot serialize: 565.0
at org.ksoap2.serialization.SoapSerializationEnvelop.writeElement(SoapSerialization.....
原因は次のとおりです.
rpc.addProperty(" ", );
ここでパラメータの値はfloat,doubleではなく,ネットで調べても資料を書いてもなぜか見つからなかった.
サーバから返されるデータがbooleanであれば、このように取得します.
SoapPrimitive soapPrimitive = (SoapPrimitive)envelope.getResponse();
boolean ret = Boolean.parseBoolean(soapPrimitive.toString());
ファイルキーのアップロード:
FileInputStream fis = new FileInputStream(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024*15];
int count = 0;
while ((count = fis.read(buffer)) >= 0) {
baos.write(buffer, 0, count);
}
String fs = new String(Base64.encodeBase64(baos .toByteArray())); fis.close();// commons-codec-1.4.jar