It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center
                            
                        
                    
                
                                7年前关闭。
            
                    
是否有可能我将我的Android应用程序中的请求发送到Web服务,并且作为回报,我从Android中解析的Web服务中获取了数据(例如XML文件)?

谢谢

kai

最佳答案

这是我编写的用于处理此问题的方法。就我而言,我将JSON用于接收的数据,因为它比XML更紧凑。我建议使用Google的GSON库将对象与json之间相互转换,如下所示:

Gson gson = new Gson();
JsonReply result = gson.fromJson(jsonResult, JsonReply.class);


JsonReply只是用于保存一些数据的pojo。您可以查看有关如何使用gson的Google Java文档。另外我必须说这种方法适用于各种字符。我主要将其用于西里尔西里尔文数据。

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;
}


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

08-17 21:06
查看更多