整理http工具类方便以后进行http通信
get请求
/**
* get请求
*
* @param url
* @param uid
* @param token
* @return
* @throws IOException
*/
public static String doGet(String url, Long uid, String token) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建get请求对象
HttpGet httpGet = new HttpGet(url);
//设置必要的请求头参数
if (!ObjectUtils.isEmpty(uid)) {
httpGet.addHeader("uid", uid.toString());
}
if (!StringUtils.isEmpty(token)) {
httpGet.addHeader("accessToken", token);
}
CloseableHttpResponse response = null;
String content = null;
try {
response = httpclient.execute(httpGet);
//当请求成功后获得回复数据
if (response.getStatusLine().getStatusCode() == 200) {
content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}
} catch (Exception e) {
//打印错误日志信息
log.error(e.getMessage());
} finally {
if (response != null) {
try {
//关闭流
response.close();
httpclient.close();
} catch (IOException e) {
log.error(e.getMessage());
}
}
}
return content;
}
post请求
/**
* @Title: doPost
* @Description: application/x-www-form-urlencoded编码方式带参数和请求头的POST请求
* @param: url
* @param: param
* @param: header
* @Date: 2019-05-27 15:27
* @return: java.lang.String
* @throws:
*/
public static String doPost(String url, Map<String, Object> param, Map<String, Object> header) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
if (header != null) {
//遍历请求头参数列表,将其放入请求头中
for (String key : header.keySet()) {
httpPost.setHeader(key, header.get(key).toString());
}
}
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key).toString()));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}