json ライブラリを使用して、json を REST サービスにポストします。
public String addPerson() {
HttpClient client = new DefaultHttpClient();
String request_string = null;
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
HttpResponse response;
try {
HttpPost post = new HttpPost(ServiceConstant.ACTIVATElICENCE);
Log.e("url", ""+ServiceConstant.ACTIVATElICENCE);
post.setHeader("Content-type", "application/x-www-form-urlencoded");
ActivationBean personactivationdata = new ActivationBean();
try {
personactivationdata.setPersonID(PersonId);
personactivationdata.setActivationKey(ActivationKey);
personactivationdata.setDeviceID(MyPreferences.getInstance(
sContext).getDeviceId());
personactivationdata.setRegistrationID(MyPreferences
.getInstance(sContext).getDeviceRegistrationId());
request_string = convertBeanToJson(personactivationdata);
} catch (Exception e) {
}
request_string = request_string.replace("\\", "")
.replace("\"[", "[").replace("]\"", "]");
request_string = request_string.replace("\n", "").replace("\r", "");
Log.e("req string for activation", "" + request_string);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair(
ServiceConstant.RequestData, request_string));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
response = client.execute(post);
/* Checking response */
if (response != null) {
InputStream inputStream = response.getEntity().getContent(); // Get
request_string = convertStreamToString(inputStream);
Log.e("response",
"response of post = " + request_string.toString());
return request_string;
}
} catch (IOException e) {
request_string = "timeout";
e.printStackTrace();
} catch (Exception e) {
// Toast.makeText(sContext, "Server Error",
// Toast.LENGTH_LONG).show();
e.printStackTrace();
}
return request_string;
}
private String convertBeanToJson(ActivationBean bean) {
String reqQuery = null;
try {
reqQuery = mapperObj.writeValueAsString(bean);
Log.d("convertBeanToJson(): request query is:", reqQuery);
} catch (JsonGenerationException e) {
Log.e("convertBeanToJson():", " caught JsonGenerationException");
} catch (JsonMappingException e) {
// mELogger.error("convertBeanToJson(): caught JsonMappingException");
} catch (IOException e) {
Log.e("convertBeanToJson():", " caught IOException");
}
return reqQuery;
}