码迷,mamicode.com
首页 > Web开发 > 详细

【HttpClient4.5中文教程】【第一章 :基础】1.1执行请求(三)

时间:2015-07-31 18:33:01      阅读:329      评论:0      收藏:0      [点我收藏+]

标签:


更多HttpClient4.5中文教程请查看点击打开链接
===============================================

1.1.7.生产实体内容

HttpClient提供了几个类,用来通过HTTP连接高效地传输内容。这些类的实例均与内含实体请求有关,比如POST和PUT,它们能够把实体内容封装进友好的HTTP请求中。对于基本的数据容器String, byte array, input stream, and file,HttpClient为它们提供了几个对应的类:StringEntity, ByteArrayEntity, InputStreamEntity, and FileEntity。
File file = new File("somefile.txt");
FileEntity entity = new FileEntity(file,ContentType.create("text/plain", "UTF-8"));
HttpPost httppost = new HttpPost("http://localhost/action.do");
httppost.setEntity(entity);
请注意InputStreamEntity是不可重复的,因为它仅仅能够从数据流中读取一次。一般建议实现一个定制的HttpEntity类来代替使用一般的InputStreamEntity。FileEntity将会是一个好的出发点。

1.1.7.1 HTML表单

许多应用需要模仿一个登陆HTML表单的过程,比如:为了登陆一个web应用或者提交输入的数据。HttpClient提供了UrlEncodedFormEntity类来简化这个过程。
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("param1", "value1"));
formparams.add(new BasicNameValuePair("param2", "value2"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams,
                                                          Consts.UTF_8);
HttpPost httppost = new HttpPost("http://localhost/handler.do");
httppost.setEntity(entity);
UrlEncodedFormEntity实例像上面一样使用URL编码方式来编码参数并生成下面的内容:
param1=value1&param2=value2

1.1.7.2 内容分块

通常,我们推荐让HttpClient选择基于被传递的HTTP报文属相最合适的传输编码方式。可能地,可以通过设置HttpEntity#setChunked()为true来通知HttpClient你要进行分块编码。注意HttpClient将会使用这个标志作为提示。当使用一些不支持分块编码的HTTP版本(比如HTTP/1.0.)时,这个值将会忽略。
译者:分块编码是是HTTP1.1协议中定义的Web用户向服务器提交数据的一种方法

StringEntity entity = new StringEntity("important message",
                           ContentType.create("plain/text", Consts.UTF_8));
entity.setChunked(true);
HttpPost httppost = new HttpPost("http://localhost/acrtion.do");
httppost.setEntity(entity);

1.1.8.响应处理器

最简单、最方便的方式来处理响应是使用ResponseHandler接口,它包含了一个handleResponse(HttpResponse response)方法。这个方法减轻使用者对于连接管理的担心。
当你使用ResponseHandler时,无论是请求执行成功亦或出现异常,HttpClient将会自动地确保连接释放回连接管理器中。
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/json");
ResponseHandler<MyJsonObject> rh = new ResponseHandler<MyJsonObject>() {
    @Override
    public JsonObject handleResponse(final HttpResponse response) throws IOException {
        StatusLine statusLine = response.getStatusLine();
        HttpEntity entity = response.getEntity();
        if (statusLine.getStatusCode() >= 300) {
            throw new HttpResponseException(statusLine.getStatusCode(),
                statusLine.getReasonPhrase());
        }
        if (entity == null) {
             throw new ClientProtocolException("Response contains no content");
        }
        Gson gson = new GsonBuilder().create();
        ContentType contentType = ContentType.getOrDefault(entity);
        Charset charset = contentType.getCharset();
        Reader reader = new InputStreamReader(entity.getContent(), charset);
        return gson.fromJson(reader, MyJsonObject.class);
    }
};
MyJsonObject myjson = client.execute(httpget, rh);

版权声明:本文为博主原创文章,未经博主允许不得转载。

【HttpClient4.5中文教程】【第一章 :基础】1.1执行请求(三)

标签:

原文地址:http://blog.csdn.net/u011179993/article/details/47172215

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!