【HttpClient4.5中文教程】【第一章 :基

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

分类:HttpClient4.5中文翻译Java基础

更多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("");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("");httppost.setEntity(entity);UrlEncodedFormEntity实例像上面一样使用URL编码方式来编码参数并生成下面的内容:param1=value1&param2=value21.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("");httppost.setEntity(entity);1.1.8.响应处理器最简单、最方便的方式来处理响应是使用ResponseHandler接口,它包含了一个handleResponse(HttpResponse response)方法。这个方法减轻使用者对于连接管理的担心。当你使用ResponseHandler时,无论是请求执行成功亦或出现异常,HttpClient将会自动地确保连接释放回连接管理器中。CloseableHttpClient httpclient = HttpClients.createDefault();HttpGet httpget = new HttpGet("");ResponseHandler<MyJsonObject> rh = new ResponseHandler<MyJsonObject>() {@Overridepublic 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实训】一.GET请求访问新浪网(非原文教程)

顶1踩0

放弃等于又一次可以选择的机会。

【HttpClient4.5中文教程】【第一章 :基

相关文章:

你感兴趣的文章:

标签云: