使用android从Web服务发送和接收数据

时间:2010-05-18 04:39:22

标签: android web-services request

我是否有可能从我的Android应用程序向Web服务发送请求,作为回报,我从Web服务获取数据,例如我在Android中解析的XML文件?

由于

1 个答案:

答案 0 :(得分:2)

这是我为处理这个而写的方法。在我的情况下,我使用JSON来获取我收到的数据,因为它比XML更紧凑。我建议使用Google的GSON库将对象转换为json或从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;
}

我希望这会有所帮助。 玩得开心:))