Java 读取 HttpPost 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4361601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 16:29:58  来源:igfitidea点击:

Reading HttpPost response

javaandroidhttp

提问by Espen

I'm using this code to post a request to a http server:

我正在使用此代码向 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 ) {
    ...
}

The response is nothing more than a simple String. How can I read this response as a String? It doesn't seem like HttpResponse have a method for doing this directly.

回应无非是一个简单的String. 我怎么能把这个回复读成一个String?HttpResponse 似乎没有直接执行此操作的方法。

采纳答案by Aliostad

I have created this helper method for sending data and special headers by POST method in Android (headers HashMap could be empty if you do not have any custom headers):

我创建了这个辅助方法,用于在 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();

 } 

回答by Ratna Dinakar

response.getStatusLine();// For reading status line

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

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