Apache HttpClient 用法

2016-04-25 13:17:49   最后更新: 2016-04-26 23:31:38   访问数量:3369




org.apache.commons.httpclient.HttpClient 是 appache 提供的一套用来进行 http 网络访问的基础工具类

如今,更新的工具类则是 org.apache.http.client.HttpClient

本篇日志中,我们就来介绍一下这两个的基本用法

 

org.apache.commons.httpclient.HttpClient

<dependency> <groupId>apache-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency>

 

 

org.apache.http.client.HttpClient

<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.5</version> </dependency>

 

 

下面展示一个基于 org.apache.commons.httpclient.HttpClient 封装的类,也就是 org.apache.commons.httpclient.HttpClient 的基本用法:

package com.sankuai.web.order.util.common; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import java.io.IOException; import java.util.Map; /** * Created by techlog on 16/4/14. * * Http 读写工具类, 提供基本的 get\post 功能, 如需设定超时, connectiontimeout 与 readtimeout 需同时提供(毫秒) * 非 withTimeout 方法或 connectiontimeout 与 readtimeout 某个参数为 0, 则取默认值: connectiontimeout(500), readtimeout(1000) */ public class HttpClientUtil { /** * post 方法 * @param url * @param params * @return * @throws IOException */ public static String post(String url, Map<String, String> params) throws IOException { return postWithTimeout(url, params, 0, 0); } /** * 具有 BA 认证及超时时间(毫秒)的 post 方法 * @param url * @param params * @param connectiontimeout * @param readtimeout * @return * @throws IOException */ public static String postWithTimeout(String url, Map<String, String> params, int connectiontimeout, int readtimeout) throws IOException { HttpClient client = new HttpClient(); if (connectiontimeout > 0) { client.getHttpConnectionManager().getParams().setConnectionTimeout(connectiontimeout); } else { client.getHttpConnectionManager().getParams().setConnectionTimeout(500); } if (readtimeout > 0) { client.getHttpConnectionManager().getParams().setSoTimeout(readtimeout); } else { client.getHttpConnectionManager().getParams().setSoTimeout(1000); } PostMethod method = new PostMethod(url); if (params != null) { for (Map.Entry<String, String> entity : params.entrySet()) { method.addParameter(entity.getKey(), entity.getValue()); } } client.executeMethod(method); return method.getResponseBodyAsString(); } /** * get 方法 * @param url * @return * @throws IOException */ public static String get(String url) throws IOException { return getWithTimeout(url, 0, 0); } /** * 带有 BA 认证与超时时间(毫秒)的 get 方法 * @param url * @param connectiontimeout * @param readtimeout * @return * @throws IOException */ public static String getWithTimeout(String url, int connectiontimeout, int readtimeout) throws IOException { HttpClient client = new HttpClient(); if (connectiontimeout > 0) { client.getHttpConnectionManager().getParams().setConnectionTimeout(connectiontimeout); } else { client.getHttpConnectionManager().getParams().setConnectionTimeout(500); } if (readtimeout > 0) { client.getHttpConnectionManager().getParams().setSoTimeout(readtimeout); } else { client.getHttpConnectionManager().getParams().setSoTimeout(1000); } GetMethod method = new GetMethod(url); client.executeMethod(method); return method.getResponseBodyAsString(); } }

 

 

下面展示一个基于 org.apache.http.client.HttpClient 封装的类,也就是 org.apache.http.client.HttpClient 的基本用法:

package com.sankuai.web.order.util.common; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Created by techlog on 16/4/25. */ public class HttpClient { public static String get(String url, int connectiontimeout, int readtimeout) throws IOException { RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(connectiontimeout) .setSocketTimeout(readtimeout) .setConnectionRequestTimeout(connectiontimeout) .build(); HttpGet get = new HttpGet(url); get.setConfig(requestConfig); HttpResponse response = (new DefaultHttpClient()).execute(get); if (response.getStatusLine().getStatusCode() == 200) return EntityUtils.toString(response.getEntity(), "utf-8"); return null; } public static String post(String url, Map<String, String> params, int connectiontimeout, int readtimeout) throws IOException { RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(connectiontimeout) .setSocketTimeout(readtimeout) .setConnectionRequestTimeout(connectiontimeout) .build(); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> paramsEntry : params.entrySet()) { formparams.add(new BasicNameValuePair(paramsEntry.getKey(), paramsEntry.getValue())); } HttpEntity reqEntity = new UrlEncodedFormEntity(formparams, "utf-8"); HttpPost post = new HttpPost(url); post.setConfig(requestConfig); HttpResponse response = (new DefaultHttpClient()).execute(post); if (response.getStatusLine().getStatusCode() == 200) return EntityUtils.toString(response.getEntity(), "utf-8"); return null; } }

 

 

下面的例子展示了 HTTP 连接池的用法:

package com.sankuai.web.order.util.common; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; /** * Created by techlog on 16/4/25. */ public class HttpClient { private static HttpClientBuilder httpBulder = null; private static RequestConfig requestConfig = null; static { requestConfig = RequestConfig.custom() .setSocketTimeout(1000) .setConnectTimeout(500) .setConnectionRequestTimeout(500) .build(); //设置http的状态参数 httpBulder = HttpClients.custom(); } public static void setConfig(int connectiontimeout, int readtimeout, int maxconnection, int maxperconnection) { requestConfig = RequestConfig.custom() .setSocketTimeout(readtimeout) .setConnectTimeout(connectiontimeout) .setConnectionRequestTimeout(connectiontimeout) .build(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(maxconnection); connectionManager.setDefaultMaxPerRoute(maxperconnection); httpBulder.setConnectionManager(connectionManager); } public static CloseableHttpClient getConnection() { return httpBulder.build(); } public static HttpUriRequest getRequestMethod(String url, String method, Map<String, String> params) { List<NameValuePair> paramsPair = new ArrayList<>(); if (params != null) { Set<Map.Entry<String, String>> entrySet = params.entrySet(); for (Map.Entry<String, String> e : entrySet) { String name = e.getKey(); String value = e.getValue(); NameValuePair pair = new BasicNameValuePair(name, value); paramsPair.add(pair); } } HttpUriRequest reqMethod = null; if ("post".equals(method)) { reqMethod = RequestBuilder.post().setUri(url) .addParameters(paramsPair.toArray(new BasicNameValuePair[paramsPair.size()])) .setConfig(requestConfig).build(); } else if ("get".equals(method)) { reqMethod = RequestBuilder.get().setUri(url) .addParameters(paramsPair.toArray(new BasicNameValuePair[paramsPair.size()])) .setConfig(requestConfig).build(); } return reqMethod; } }

 

 

调用时,首先通过 getConnection 方法获取 HttpClient 对象,然后通过 getRequestMethod 方法获取 HttpUriRequest 对象,通过 HttpUriRequest 对象作为参数调用 HttpClient 的 execute 方法即可完成调用

 

Apache Software Foundation -- http://hc.apache.org/httpcomponents-client-ga/examples.html

HttpComponents之httpclient基本使用方法 -- http://my.oschina.net/xinxingegeya/blog/282683

 






技术帖      apache      技术分享      http      java      maven      commons      httpclient      get      post      util      utils     


京ICP备15018585号