Http请求工具类
这里采用apache提供的httpclient实现
首先导入相关依赖
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
为了方便打印请求和响应,这里是有 log4j作为日志 fastjson作为转json工具类
以下是代码:
package com.lichong.http;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.*;
/**
* Http请求工具类
* @author:LiChong
* @date:2018/7/26
*/
public class HttpUtils {
private static final Logger logger = LogManager.getLogger(HttpUtils.class);
/**
* get请求
* @param url
* @param params
* @return
*/
public static String doGet(String url, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
// 创建参数列表
URIBuilder uriBuilder = new URIBuilder(url);
for (String key : params.keySet()) {
uriBuilder.setParameter(key, params.get(key).toString());
}
logger.info("GET 请求...." + url + ",params:" + JSON.toJSONString(params));
HttpGet httpGet = new HttpGet(uriBuilder.build());
// 执行请求
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(entity, "UTF-8");
}
} catch (URISyntaxException e) {
e.printStackTrace();
logger.error(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
logger.error(e.getMessage());
} finally {
if (httpClient != null) {
try {
httpClient.close();
response.close();
} catch (IOException e) {
e.printStackTrace();
logger.error(e.getMessage());
}
}
}
return null;
}
/**
* post请求
* @param url
* @param params
* @return
*/
public static String doPost(String url, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost post = new HttpPost(url);
// 创建参数列表
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
list.add(new BasicNameValuePair(key, params.get(key).toString()));
}
// url格式编码
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(list, "UTF-8");
post.setEntity(uefEntity);
post.setHeader("ContentType", "application/json");
logger.info("POST 请求...." + url + ",params:" + JSON.toJSONString(params));
// 执行请求
HttpResponse httpResponse = httpClient.execute(post);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
logger.error(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
logger.error(e.getMessage());
} finally {
try {
if (httpClient != null) {
httpClient.close();
}
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
}
}
return null;
}
public static void main(String[] args) {
Map<String,Object> params = new HashMap<>();
params.put("name","LC");
String getResult = HttpUtils.doGet("www.baidu.com", params);
System.out.println("GET请求结果" + getResult);
String postReuslt = HttpUtils.doPost("www.baidu.com", params);
System.out.println("POST请求结果" + postReuslt);
}
}