阅读HttpPost响应 [英] Reading HttpPost response

查看:184
本文介绍了阅读HttpPost响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这个code张贴到HTTP服务器的请求:

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

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 ) {
    ...
}

响应只不过是一个简单的字符串更多。我怎么能看这种反应为字符串?它似乎并不像Htt的presponse有直接这样做的方法。

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.

推荐答案

我创造了这个helper方法,在Android的由POST方法发送的数据和特殊的头(头HashMap的可能是空的,如果你没有任何自定义页眉):

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):

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();

 } 

这篇关于阅读HttpPost响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆