我已经使用
成功将我的Android应用程序连接到C#WCF Web服务DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(SERVICE_URI);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
HttpResponse response = client.execute(request);
这与我的WCF服务上的HttpGet方法匹配。我现在的问题是如何调整此代码以与C#webservice中的REST WebInvoke方法进行通信,如下所示
[OperationContract]
[WebInvoke(
Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/GetItems"
)]
GetItemsResponse GetItems(GetItemsRequest request);
如何在android中与此方法进行通信?是否有像HttpGet一样内置的东西,还是需要某种第三方Android-REST库?
答案 0 :(得分:0)
首先,在Android无法在主线程中执行网络任务时,必须执行异步操作 创建此类
private class SomeServiceRequest extends AsyncTask<JSONObject, Long, JSONObject> {
@Override
protected JSONObject doInBackground(JSONObject... params) {
HttpPost request = new HttpPost(SERVICE_URI);
request.setHeader("Accept", "application/json; charset=utf-8");
request.setHeader("Content-type", "application/json; charset=utf-8");
JSONObject result = null;
// Build JSON string
try {
StringEntity entity = new StringEntity(params[0].toString(),
"UTF-8");
request.setEntity(entity);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
StatusLine sl = response.getStatusLine();
if (sl.getStatusCode() == 200) {
result = new JSONObject(EntityUtils.toString(response
.getEntity()));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(JSONObject result) {
processSvcResult(result);
super.onPostExecute(result);
}
}
此代码用于处理响应
private void processSvcResult(JSONObject result) {
if (result != null) {
try {
Boolean success = result.getString("Status").equals("OK");
storeRegistrationSuccess(context, success);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
使用它样本
private void CallSomeService(String messageId) {
final SharedPreferences prefs = getSharedPreferences(
this.getClass().getSimpleName(), Context.MODE_PRIVATE);
// PROPERTY_IDDEVICE
String iddevice = prefs.getString(PROPERTY_IDDEVICE, "");
JSONObject p = new JSONObject();
try {
p.put("IDDevice", iddevice.toLowerCase(Locale.ROOT));
p.put("MessageID", messageId);
new SomeServiceRequest().execute(p);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}