wustguangh |分类标签:Android 2015-01-31
Android使用KSoap2如何以json方式请求WebService
Android使用KSoap2包访问WebService介绍KSoap2包在Android项目中的基本用法,但如果希望使用KSoap2以json方式请求WebService如何实现呢?
满意答案
wustguangh 19级 2015-01-31 08:33:02
下面的代码使用json方式请求WebService:
public String doSetObject() throws JSONException { Log.i("[WebService]", "doSetObject"); String rs = ""; SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME2); JSONObject json = new JSONObject(); json.put("name", "milkmidi"); json.put("age", "30"); request.addProperty("json", json.toString()); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); try { androidHttpTransport.call(MemberLogin_SOAP_ACTION, envelope); SoapPrimitive result = (SoapPrimitive) envelope.getResponse(); rs = result.toString(); } catch (Exception e) { TextView mMsgTxt = (TextView) (findViewById(Sanzond.Common.R.id.mMsgTxt)); mMsgTxt.setText(e.toString()); } JSONObject rsJson = new JSONObject(rs); return rsJson.getString("name") + "," + rsJson.getString("age"); }
使用json是经常使用的方式,KSoap2也为我们提供了便捷的途径,只需要调用SoapObject对象的addProperty函数时将第一个参数设置为“json”,第二个参数是对应的json数据对象。再将这个SoapObject对象作为SoapSerializationEnvelope的成员函数setOutputSoapObject的参数使用。