发送和采用了android从Web服务接收数据 [英] Sending and receiving data from a web service using android
问题描述
是有可能,我送从我的Android应用程序的请求到Web服务,作为回报,我得到例如数据从Web服务的XML文件,这是我在Android的解析?
is it possible that I send a request from my Android app to a web service and in return I get a data for example a XML file from the web service which I parse in android?
感谢
佳
推荐答案
这是我写的处理只是一个方法。以我为例,我使用JSON为我收到的数据,因为它比XML更加紧凑。我建议使用谷歌的GSON库对象转换为从JSON这样的:
This is a method I wrote for handling just that. In my case I am using JSON for the data that I recieve, because it is much more compact than XML. I suggest using Google's GSON library for converting objects to and from json like that:
Gson gson = new Gson();
JsonReply result = gson.fromJson(jsonResult, JsonReply.class);
在哪里JsonReply仅仅是拿着一些数据的POJO。你可以看到谷歌的有关如何在您的情况下使用GSON Java文档。此外,我必须说,这种方法适用于各种人物。我使用它主要用于sendign西里尔数据。
Where JsonReply is just a pojo for holding some data. You can see Google's java docs about how to use gson in your case. In addition I must say that this method works with all kinds of characters. I am using it mostly for sendign cyrillic 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;
}
我希望这有助于。
玩得开心:)
I hope this helps. Have fun :)
这篇关于发送和采用了android从Web服务接收数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!