HttpClient 4.X代码样例备忘.其中httpClient 4.0与httpClient 4.3+代码结构少有不同.
1. httpClient 4.0
public class HttpClientUtil { private final static Log log = LogFactory.getLog(HttpClientUtil.class); private static HttpClient httpClient = new DefaultHttpClient();; public static final String CHARSET = "UTF-8"; static { httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 15000); } public static String httpGet(String url, Map<String, String> params){ return httpGet(url, params,"utf-8"); } public static String httpPost(String url, Map<String, String> params){ return httpPost(url, params,"utf-8"); } /** * @param url http://taobao.com/test.action * @param params 参数,编码之前的参数 * @return */ public static String httpGet(String url, Map<String, String> params,String charset) { if(StringUtils.isBlank(url)){ return null; } try { if(params != null && !params.isEmpty()){ List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size()); for(Entry<String,String> entry : params.entrySet()){ String value = entry.getValue(); if(value != null){ pairs.add(new BasicNameValuePair(entry.getKey(),value)); } } url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset)); } HttpGet httpget = new HttpGet(url); HttpResponse response = httpClient.execute(httpget); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { httpget.abort(); throw new RuntimeException("HttpClient,error status code :" + statusCode); } HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); return result; } catch (Exception e) { log.error("http调用异常!url:" + url, e); } finally { httpClient.getConnectionManager().closeIdleConnections(30, TimeUnit.SECONDS); } return null; } /** * @param url http://360buy.com/test.action * @param params 参数,编码之前的参数 * @return */ public static String httpPost(String url, Map<String, String> params,String charset) { if(StringUtils.isBlank(url)){ return null; } try{ HttpPost httpPost = new HttpPost(url); if(params != null && !params.isEmpty()){ List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size()); for(Entry<String,String> entry : params.entrySet()){ String value = entry.getValue(); if(value != null){ pairs.add(new BasicNameValuePair(entry.getKey(),value)); } } httpPost.setEntity(new UrlEncodedFormEntity(pairs,charset)); } HttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { httpPost.abort(); throw new RuntimeException("HttpClient,error status code :" + statusCode); } HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); return result; } catch (Exception e) { log.error("http调用异常!url:" + url, e); } finally { httpClient.getConnectionManager().closeIdleConnections(30, TimeUnit.SECONDS); } return null; } /** * 发送body为form格式 * @param url * @return * @throws Exception */ public static String httpPost(String url,Map<String,String> params,HttpEntity requestEntity) throws Exception{ if(params != null && !params.isEmpty()) { List<NameValuePair> pairs = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : params.entrySet()) { String value = entry.getValue(); if (value != null) { pairs.add(new BasicNameValuePair(entry.getKey(), value)); } } String queryString = EntityUtils.toString(new UrlEncodedFormEntity(pairs, CHARSET)); if(url.indexOf("?") > 0) { url += "&" + queryString; } else { url += "?" + queryString; } } HttpPost httpPost = new HttpPost(url); if(requestEntity != null) { httpPost.setEntity(requestEntity); } CloseableHttpResponse response = httpClient.execute(httpPost); try { HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); return result; } finally { response.close(); } }
2. httpClient 4.3+
public class HttpClientUtil { private static final CloseableHttpClient httpClient; public static final String CHARSET = "UTF-8"; static { RequestConfig config = RequestConfig.custom() .setConnectTimeout(60000) .setSocketTimeout(15000) .build(); httpClient = HttpClientBuilder.create() .setDefaultRequestConfig(config) .build(); } public static String httpGet(String url, Map<String, String> params){ return httpGet(url, params,"utf-8"); } /** * @param url http://taobao.com/test.action * @param params 参数,编码之前的参数 * @return */ public static String httpGet(String url, Map<String, String> params,String charset) { if(StringUtils.isBlank(url)){ return null; } try { if(params != null && !params.isEmpty()){ List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size()); for(Map.Entry<String,String> entry : params.entrySet()){ String value = entry.getValue(); if(value != null){ pairs.add(new BasicNameValuePair(entry.getKey(),value)); } } url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset)); } HttpGet httpget = new HttpGet(url); CloseableHttpResponse response = httpClient.execute(httpget); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { httpget.abort(); throw new RuntimeException("HttpClient,error status code :" + statusCode); } HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); response.close(); return result; } catch (Exception e) { e.printStackTrace(); } return null; } }
3. httpClient 4.3+中cookie操作
public class HttpUtils { private static final CloseableHttpClient httpClient; public static final String CHARSET = "UTF-8"; static { RequestConfig config = RequestConfig.custom() .setConnectTimeout(6000) .setSocketTimeout(6000) .build(); Registry<CookieSpecProvider> registry = RegistryBuilder.<CookieSpecProvider>create() .register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory()) .register(CookieSpecs.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactory()) .build(); httpClient = HttpClients.custom() .setDefaultRequestConfig(config) .setDefaultCookieSpecRegistry(registry) .setDefaultCookieStore(new BasicCookieStore()) //内存中 .build(); } public static void main(String[] args) throws Exception{ login();//server 端写cookie getOrder();//客户端发送cookie } public static void getOrder() throws Exception{ String url = "http://test.domain/user/order.jhtml"; HttpGet httpGet = new HttpGet(url); HttpClientContext clientContext = HttpClientContext.create(); //默认情况下,httpClient会发送所有的,已接受到的cookie,无需额外的操作 //如果client需要发送额外的cookie值,可以通过如下方式替换 /** CookieStore cookieStore = new BasicCookieStore(); List<Cookie> cookies = cookieStore.getCookies(); for(Cookie cookie : cookies) { cookieStore.addCookie(cookie); } clientContext.setCookieStore(cookieStore); **/ CloseableHttpResponse response = httpClient.execute(httpGet,clientContext); try { HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); System.out.println(result); } finally { response.close(); } } public static void login() throws Exception{ String url = "http://test.domain/user/login.jhtml"; Map<String,String> params = new HashMap<String,String>(); params.put("phone","18600000000"); params.put("password","123123"); if(params != null && !params.isEmpty()) { List<NameValuePair> pairs = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : params.entrySet()) { String value = entry.getValue(); if (value != null) { pairs.add(new BasicNameValuePair(entry.getKey(), value)); } } url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, CHARSET)); } HttpPost httpPost = new HttpPost(url); HttpClientContext clientContext = HttpClientContext.create(); CloseableHttpResponse response = httpClient.execute(httpPost,clientContext); try { HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); System.out.println(result);//响应的结果 //获取响应中包含或者"新增"的cookie信息 //这些cookie会被保存在HttpClient全局的cookieStore中,以便此后其他请求使用 CookieStore cookieStore = clientContext.getCookieStore(); List<Cookie> cookies = cookieStore.getCookies(); for(Cookie cookie : cookies) { System.out.println(cookie.getName() + "," + cookie.getValue()); } } finally { response.close(); } } }
4. httpClient与multipart-form提交
String url = "http://test.domain/update_user.jhtml"; HttpPost post = new HttpPost(url); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); FileBody fileBody = new FileBody(new File("D:\\test.jpg")); entityBuilder.addPart("icon",fileBody);//发送图片 ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8")); StringBody stringBody = new StringBody("张三",contentType); entityBuilder.addPart("name",stringBody); post.setEntity(entityBuilder.build()); CloseableHttpResponse response = httpClient.execute(post); HttpEntity entity = response.getEntity(); String result = null; System.out.println(response.getStatusLine()); if (entity != null) { long length = entity.getContentLength(); System.out.println(length); if (length != -1) { result = EntityUtils.toString(entity, "utf-8"); } } else { System.out.println("11:null"); } EntityUtils.consume(entity); response.close();
5. pom.xml
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.1</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.3</version> </dependency>