【问题标题】:Sending and receiving data from a web service using android [closed]使用android从Web服务发送和接收数据[关闭]
【发布时间】:2010-05-18 04:39:22
【问题描述】:
我是否有可能从我的 Android 应用程序向 Web 服务发送一个请求,然后我会从我在 android 中解析的 Web 服务中获取一个数据,例如 XML 文件?
谢谢
开
【问题讨论】:
标签:
android
web-services
request
【解决方案1】:
这是我为处理这个问题而编写的一种方法。在我的例子中,我使用 JSON 作为我收到的数据,因为它比 XML 更紧凑。我建议使用 Google 的 GSON 库来像这样将对象与 json 相互转换:
Gson gson = new Gson();
JsonReply result = gson.fromJson(jsonResult, JsonReply.class);
JsonReply 只是用于保存一些数据的 pojo。您可以查看 Google 的 java 文档,了解如何在您的情况下使用 gson。另外我必须说这个方法适用于各种字符。我主要将它用于发送西里尔数据。
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;
}
我希望这会有所帮助。
玩得开心:)