阅读HttpPost响应

时间:2010-12-05 22:19:40

标签: java android http

我正在使用此代码将请求发布到http服务器:

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost( "http://192.168.0.1/test.php" );
HttpResponse response = null;
try {
    List< NameValuePair > nameValuePairs = new ArrayList< NameValuePair >( 1 );
    nameValuePairs.add( new BasicNameValuePair( "num", "2" ) );
    post.setEntity( new UrlEncodedFormEntity( nameValuePairs ) );
    response = client.execute( post );
}
catch( ClientProtocolException e ) {
    ...
}
catch( IOException e ) {
    ...
}

回复只不过是一个简单的String。如何以String的形式阅读此回复?似乎HttpResponse没有直接执行此操作的方法。

2 个答案:

答案 0 :(得分:10)

我已经创建了这个辅助方法,用于在Android中通过POST方法发送数据和特殊标题(如果你没有任何自定义标题,标题HashMap可能是空的):

public static String getStringContent(String uri, String postData, 
        HashMap<String, String> headers) throws Exception {

        HttpClient client = new DefaultHttpClient();
        HttpPost request = new HttpPost();
        request.setURI(new URI(uri));
        request.setEntity(new StringEntity(postData));
        for(Entry<String, String> s : headers.entrySet())
        {
            request.setHeader(s.getKey(), s.getValue());
        }
        HttpResponse response = client.execute(request);

        InputStream ips  = response.getEntity().getContent();
        BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
        if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK)
        {
            throw new Exception(response.getStatusLine().getReasonPhrase());
        }
        StringBuilder sb = new StringBuilder();
        String s;
        while(true )
        {
            s = buf.readLine();
            if(s==null || s.length()==0)
                break;
            sb.append(s);

        }
        buf.close();
        ips.close();
        return sb.toString();

 } 

答案 1 :(得分:5)

response.getStatusLine(); //用于阅读状态行

org.apache.http.util.EntityUtils.toString(response.getEntity());