HttpClient学习笔记
HttpClient相关的实体类官方文档地址:http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/
HttpGet HttpGet=new HttpGet(“http://www.baidu.com”); httpClient.execute(httpGet);
HttpPost httpPost=new HttpPost(“http://www.baidu.com”); List<NameValuePair>params=newArrayList<NameValuePair>(); Params.add(new BasicNameValuePair(“username”,”admin”)); Params.add(new BasicNameValuePair(“password”,”123456”)); UrlEncodedFormEntity entity=newUrlEncodedFormEntity(params,”utf-8”); httpPost.setEntity(entity); HttpClient.execute(HttpPost);
If(httpResponse.getStatusLine().getStatusCode()==200){ //请求和响应都成功了 HttpEntityentity=HttpResponse.getEntity();//调用getEntity()方法获取到一个HttpEntity实例 //用EntityUtils.toString()这个静态方法将HttpEntity转换成字符串,防止服务器返回的数据带有中文,所以在转换的时候将字符集指定成utf-8就可以了 Stringresponse=EntityUtils.toString(entity,”utf-8”); }6. 释放连接。无论执行方法是否成功,都必须释放连接。
GET请求示例代码:
public static String HttpGet(String url) { // 关闭HttpClient系统日志; System.setProperty("org.apache.commons.logging.Log","org.apache.commons.logging.impl.SimpleLog"); System.setProperty("org.apache.commons.logging.simplelog.showdatetime","true"); System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient","stdout"); HttpClient httpClient = new DefaultHttpClient(); HttpGet get = new HttpGet(url); HttpResponse response = null; HttpEntity httpEntity = null; String content = null; try { response = httpClient.execute(get); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { //判断gzip,解压缩 if(!ObjectUtil.isEmpty(response.getLastHeader("Content-Encoding")) && (response.getLastHeader("Content-Encoding").toString()).indexOf("gzip")>=0){ response.setEntity(new GzipDecompressingEntity(response.getEntity())); } httpEntity = response.getEntity(); content = EntityUtils.toString(httpEntity); } } catch (Exception e) { e.printStackTrace(); } finally { if (null != httpEntity) { try { httpEntity.consumeContent();//已经弃用 } catch (IOException e) { e.printStackTrace(); } } } return content; }
POST请求示例代码:
/** * @param url * @param data (以流的方式发送请求参数) * @return */ public static String HttpPost(String url, String data) { // 关闭HttpClient系统日志; System.setProperty("org.apache.commons.logging.Log","org.apache.commons.logging.impl.SimpleLog"); System.setProperty("org.apache.commons.logging.simplelog.showdatetime","true"); System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient","stdout"); HttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost(url); HttpResponse response = null; HttpEntity httpEntity = null; String content = null; try { StringEntity entity = new StringEntity(data,"UTF-8"); post.setEntity(entity); response = httpClient.execute(post); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { httpEntity = response.getEntity(); content = EntityUtils.toString(httpEntity,"UTF-8"); } } catch (Exception e) { Logger.getRootLogger().error("HttpPost-流的方式:" + e.getMessage()); } finally { if (null != httpEntity) { try { httpEntity.consumeContent(); } catch (IOException e) { Logger.getRootLogger().error("HttpPost-流的方式:" + e.getMessage()); } } } return content; }释放连接注意的问题:
上述示例中使用的httpEntity.consumeContent()自从4.1版本就已经废弃,不建议使用了,建议使用InputStream.close()
on the input stream returned bygetContent()来完成。官方sample如下:
CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpGet httpget = new HttpGet("http://www.apache.org/"); // Execute HTTP request CloseableHttpResponse response = httpclient.execute(httpget); try { // Get hold of the response entity HttpEntity entity = response.getEntity(); // If the response does not enclose an entity, there is no need // to bother about connection release if (entity != null) { InputStream instream = entity.getContent();//获取流对象 try { instream.read(); // do something useful with the response } catch (IOException ex) { // In case of an IOException the connection will be released // back to the connection manager automatically throw ex; } finally { // Closing the input stream will trigger connection release instream.close(); } } } finally { response.close(); } } finally { httpclient.close(); }也可以使用EntityUtils.consume(entity); Ensures that the entity content is fully consumed and the content stream, if exists, is closed.
官方建议使用这种方法:
@Deprecated
void consumeContent()
throws IOException
Deprecated. (4.1) Use EntityUtils.consume(HttpEntity)
This method is deprecated since version 4.1. Please use standard java convention to ensure resource deallocation by calling InputStream.close() on the input stream returned by getContent()
This method is called to indicate that the content of this entity is no longer required. All entity implementations are expected to release all allocated resources as a result of this method invocation. Content streaming entities are also expected to dispose
of the remaining content, if any. Wrapping entities should delegate this call to the wrapped entity.
This method is of particular importance for entities being received from a connection. The entity needs to be consumed completely in order to re-use the connection with keep-alive.
Throws:
IOException - if an I/O error occurs.
See Also:
and #writeTo(OutputStream)