Sending and receiving data from a web service using Android
1 answer
This is the method I wrote to handle just that. In my case, I am using JSON for the data I receive because it is much more compact than XML. I suggest using the Google GSON library to convert objects to and from json:
Gson gson = new Gson();
JsonReply result = gson.fromJson(jsonResult, JsonReply.class);
Where JsonReply is just a pojo to store some data. You can see google java docs on how to use gson in your case. Also, I must say that this method works with all types of characters. I use it mainly for cyrillic sendign data.
public String postAndGetResult(String script, List<NameValuePair> postParameters){
String returnResult = "";
BufferedReader in = null;
try {
HttpParams httpParameters = new BasicHttpParams();
HttpProtocolParams.setContentCharset(httpParameters, "UTF-8");
HttpProtocolParams.setHttpElementCharset(httpParameters, "UTF-8");
HttpClient client = new DefaultHttpClient(httpParameters);
client.getParams().setParameter("http.protocol.version",
HttpVersion.HTTP_1_1);
client.getParams().setParameter("http.socket.timeout",
new Integer(2000));
client.getParams().setParameter("http.protocol.content-charset",
"UTF-8");
httpParameters.setBooleanParameter("http.protocol.expect-continue",
false);
HttpPost request = new HttpPost(SERVER + script + "?sid="
+ String.valueOf(Math.random()));
request.getParams().setParameter("http.socket.timeout",
new Integer(5000));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
postParameters, "UTF-8");
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
returnResult = sb.toString();
} catch (Exception ex) {
return "";
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
return returnResult;
}
Hope this helps. Good luck :)
+2
a source to share