HttpClent工具类
前后端分离的项目中,涉及到了多个包之间的接口调用,其中涉及到的Httpclient相关知识点,特此记录一下:
package xxxx.utils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.conn.routing.HttpRoute;
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 org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.ParseException;
public class HttpClentUtil {
private static PoolingHttpClientConnectionManager connectionManager = null;
private static HttpClientBuilder httpBuilder = null;
private static RequestConfig requestConfig = null;
private static int MAXCONNECTION = 10;
private static int DEFAULTMAXCONNECTION = 5;
private static String IP = “cnivi.com.cn”;
private static int PORT = 9066;
static {
//设置http的状态参数
requestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.build();
HttpHost target = new HttpHost(IP, -1); //不想制定具体的端口 则设置为-1
connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(MAXCONNECTION);//客户端总并行链接最大数
connectionManager.setDefaultMaxPerRoute(DEFAULTMAXCONNECTION);//每个主机的最大并行链接数
connectionManager.setMaxPerRoute(new HttpRoute(target), 20);
httpBuilder = HttpClients.custom();
httpBuilder.setConnectionManager(connectionManager);
}
public static CloseableHttpClient getConnection() {
CloseableHttpClient httpClient = httpBuilder.build();
return httpClient;
}
/**
* 从url请求资源 获取数据(支持get post)
* @param map url参数键值对
* @param url 请求路径
* @param method 请求方式 (get/post)
* @return
*/
public static String getRequest( String url, Map<String, String> map,String method) {
String strResult = “请求失败”;
HttpClient client = getConnection();
List<NameValuePair> params = new ArrayList<NameValuePair>();
Set<Map.Entry<String, String>> entrySet = map.entrySet();
for (Map.Entry<String, String> e : entrySet) {
String name = e.getKey();
String value = e.getValue();
NameValuePair pair = new BasicNameValuePair(name, value);
params.add(pair);
}
HttpUriRequest reqMethod = null;
if (“post”.equals(method.toLowerCase())) {
reqMethod = RequestBuilder.post().setUri(url)
.addParameters(params.toArray(new BasicNameValuePair[params.size()])).setConfig(requestConfig)
.build();
} else if (“get”.equals(method.toLowerCase())) {
reqMethod = RequestBuilder.get().setUri(url)
.addParameters(params.toArray(new BasicNameValuePair[params.size()])).setConfig(requestConfig)
.build();
}
System.err.println(“—————————“+reqMethod.getURI());
try {
HttpResponse response = client.execute(reqMethod);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
strResult = EntityUtils.toString(entity, “utf-8”);
}
} catch (ClientProtocolException e1) {
e1.printStackTrace();
strResult = e1.getMessage();
} catch (IOException e1) {
e1.printStackTrace();
strResult = e1.getMessage();
}
System.err.println(“—————————“+strResult);
return strResult;
}
public static void main(String args[]) throws IOException {
Map<String, String> map = new HashMap<String, String>();
map.put(“token”, “YTE0MzEwYjYtZGUyOS00YzE5LWEzMDgtNGVmZDBhYzgwNWUyOjIwMTkwNzI2MTE6NDM6NDc=”);
map.put(“id”, “1234567890”);
String URL = “http://192.168.0.195:9270/api/issue/v1/defects/testrpc”;
System.err.println(getRequest(URL, map, “get”));
System.err.println(getRequest(URL + “/post”, map, “post”));
System.err.println(get(URL, map));
System.err.println(post(URL + “/post”, map));
}
/**
* 从url请求资源 获取数据(get方式)
* @param url 请求路径
* @param mapParams url参数键值对
* @return
*/
public static String get(String url, Map<String, String> mapParams) {
String strResult=”请求失败”;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// 创建httpget.
String getUrl =url;
//键找值遍历
if (mapParams != null && mapParams.size() >= 1) {
Set<String> set1 = mapParams.keySet();
int index =1;
for (String key : set1) {
String value = mapParams.get(key);
if(index==1){
getUrl += “?” + key + “=” + value;
}else{
getUrl += “&” + key + “=” + value;
}
index++;
}
}
HttpGet httpget = new HttpGet(getUrl);
System.err.println(“—————————“+ httpget.getURI());
// 执行get请求.
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
if (entity != null) {
// 打印响应内容
strResult = EntityUtils.toString(entity);
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
strResult =e.getMessage();
} catch (ParseException e) {
e.printStackTrace();
strResult =e.getMessage();
} catch (IOException e) {
e.printStackTrace();
strResult =e.getMessage();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.err.println(“—————————” + strResult);
return strResult;
}
/**
* 从url请求资源 获取数据(post方式)
* @param url 请求路径
* @param mapParams url参数键值对
* @return
*/
public static String post(String url,Map<String, String> mapParams) {
String strResult=”请求失败”;
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost(url);
// 创建参数队列
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair(“whkp”, “softoptic”));
if (mapParams != null && mapParams.size() >= 1) {
Set<String> set1 = mapParams.keySet();
for (String key : set1){
String value = mapParams.get(key);
formparams.add(new BasicNameValuePair(key, value));
}
}
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, “UTF-8”);
httppost.setEntity(uefEntity);
System.err.println(“—————————“+ httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
strResult = EntityUtils.toString(entity, “UTF-8”);
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
strResult =e.getMessage();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
strResult =e1.getMessage();
} catch (IOException e) {
e.printStackTrace();
strResult =e.getMessage();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.err.println(“—————————” + strResult);
return strResult;
}
}
相关文章