HttpClient4.5 基础教程 执行请求<三>

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

===============================================

1.1.7.生产实体内容

HttpClient提供了几个类,用来通过HTTP连接高效地传输内容。这些类的实例均与内含实体请求有关,比如POST和PUT,它们能够把实体内容封装进友好的HTTP请求中。对于基本的数据容器String, byte array, input stream, and file,HttpClient为它们提供了几个对应的类:StringEntity, ByteArrayEntity, InputStreamEntity, and FileEntity。
  1. File file = new File(“somefile.txt”);  
  2. FileEntity entity = new FileEntity(file,ContentType.create(“text/plain”“UTF-8”));  
  3. HttpPost httppost = new HttpPost(“http://localhost/action.do”);  
  4. httppost.setEntity(entity);  
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类来简化这个过程。
  1. List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
  2. formparams.add(new BasicNameValuePair(“param1”“value1”));  
  3. formparams.add(new BasicNameValuePair(“param2”“value2”));  
  4. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams,  
  5.                                                           Consts.UTF_8);  
  6. HttpPost httppost = new HttpPost(“http://localhost/handler.do”);  
  7. httppost.setEntity(entity);  
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用户向服务器提交数据的一种方法】

  1. StringEntity entity = new StringEntity(“important message”,  
  2.                            ContentType.create(”plain/text”, Consts.UTF_8));  
  3. entity.setChunked(true);  
  4. HttpPost httppost = new HttpPost(“http://localhost/acrtion.do”);  
  5. httppost.setEntity(entity);  
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将会自动地确保连接释放回连接管理器中。
  1. CloseableHttpClient httpclient = HttpClients.createDefault();  
  2. HttpGet httpget = new HttpGet(“http://localhost/json”);  
  3. ResponseHandler<MyJsonObject> rh = new ResponseHandler<MyJsonObject>() {  
  4.     @Override  
  5.     public JsonObject handleResponse(final HttpResponse response) throws IOException {  
  6.         StatusLine statusLine = response.getStatusLine();  
  7.         HttpEntity entity = response.getEntity();  
  8.         if (statusLine.getStatusCode() >= 300) {  
  9.             throw new HttpResponseException(statusLine.getStatusCode(),  
  10.                 statusLine.getReasonPhrase());  
  11.         }  
  12.         if (entity == null) {  
  13.              throw new ClientProtocolException(“Response contains no content”);  
  14.         }  
  15.         Gson gson = new GsonBuilder().create();  
  16.         ContentType contentType = ContentType.getOrDefault(entity);  
  17.         Charset charset = contentType.getCharset();  
  18.         Reader reader = new InputStreamReader(entity.getContent(), charset);  
  19.         return gson.fromJson(reader, MyJsonObject.class);  
  20.     }  
  21. };  
  22. MyJsonObject myjson = client.execute(httpget, rh);  
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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值