解析post方法的响应

时间:2011-03-31 12:32:19

标签: android xml apache-commons-httpclient

我将数据发布到服务器,然后以响应的形式返回发布数据... 我用这个代码

PostMethod post = new PostMethod(this._serverUrl);

        InputStream is=null;
        is = new ByteArrayInputStream(postData.getBytes("UTF-8"));

        post.setRequestEntity(new InputStreamRequestEntity(is));
        post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");

        HttpClient httpclient = new HttpClient();

        int result = httpclient.executeMethod(post);

        String response="";
        response    =   post.getResponseBodyAsString();

我使用了公共apache httpclient来发帖.... 在这里我得到回应

03-31 17:53:49.192: INFO/Response(2237): <?xml version="1.0" encoding="UTF-8"?>
03-31 17:53:49.192: INFO/Response(2237): <AndroidGame>
03-31 17:53:49.192: INFO/Response(2237):   <Result>0</Result>
03-31 17:53:49.192: INFO/Response(2237):   <ErrorCode>509</ErrorCode>
03-31 17:53:49.192: INFO/Response(2237):   <ErrorMsg>You are using wrong Super Password</ErrorMsg>
03-31 17:53:49.192: INFO/Response(2237): </AndroidGame>

但是我需要在String中得到响应....我无法在单个字符串中得到响应......它是块状的......任何人都可以帮助我

1 个答案:

答案 0 :(得分:1)

我是这样做的(我使用了不同方法的联合代码,所以它可能有点乱):

    HttpPost request = new HttpPost(url);
    List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
    postParameters.add(new BasicNameValuePair(PARAMETER_LOGIN, login));
    postParameters.add(new BasicNameValuePair(PARAMETER_PASSWORD, password));
    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters, "UTF-8");
    request.setEntity(formEntity);

    HttpResponse response = client.execute(request);

    BufferedReader in = null; 
    try {
        //Log.d("status line ", "test " + response.getStatusLine().toString());
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); 
        StringBuffer sb = new StringBuffer(""); 
        String line = ""; 
        String NL = System.getProperty("line.separator"); 
        while ((line = in.readLine()) != null) { 
            sb.append(line + NL); 
        } 
        in.close(); 
        return sb.toString();       
    } finally { 
        if (in != null) { 
            try { 
                in.close(); 
            } catch (IOException e) { 
                e.printStackTrace();
            } 
        } 
    }