Recently, I have used the three-party interface requirement of HttpClient to send post and get requests, so I wrote a package class for later use:
The maven coordinates of some jars that need to be used:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.7</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
HttpUtil package class:
package com.springboot.demo.test.service;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
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.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import java.io.*;
import java.util.Map;
public class HttpUtil {
private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
private static String chaset = "UTF-8"; // 默认编码
/**
* 发送 GET 请求(HTTP),无参数
* @param url
* @return
*/
public static String doGet(String url) {
if (StringUtils.isBlank(url)) {
return "url不能为空";
}
// 创建http GET请求
logger.info("url:{}", url);
HttpGet httpGet = new HttpGet(url);
// 设置请求和传输超时时间
httpGet.setConfig(requestConfig);
String result = "";
try (CloseableHttpClient httpclient = HttpClients.createDefault();// 创建Httpclient对象
CloseableHttpResponse response = httpclient.execute(httpGet);// 执行请求
) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity(), chaset);
logger.info("HttpGet方式请求成功!返回结果:{}", result);
} else {
logger.info("HttpGet方式请求失败!状态码:" + statusCode);
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 发送 GET 请求(HTTP),有参数
* @param url
* @param params
* @return
*/
public static String doGet(String url, Map<String, Object> params) {
if (!CollectionUtils.isEmpty(params)) {
StringBuffer extraUrl = new StringBuffer();
int temp = 0;
for (String key : params.keySet()) {
if (temp == 0) {
extraUrl.append("?");
} else {
extraUrl.append("&");
}
extraUrl.append(key).append("=").append(params.get(key));
temp++;
}
url += extraUrl;
}
return doGet(url);
}
/**
* 发送 POST 请求(HTTP),无参数
* @param url
* @return
*/
public static String doPost(String url) {
return doPost(url, null);
}
/**
* 发送 POST 请求(HTTP),有参数
* @param url
* @return
*/
public static String doPost(String url, Map<String, Object> params) {
// 创建http POST请求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
httpPost.setHeader("Content-Type", "application/json");
if (params != null) {
httpPost.setEntity(new StringEntity(JSON.toJSONString(params), ContentType.create("application/json", "utf-8")));
}
String result = "";
try (CloseableHttpClient httpclient = HttpClients.createDefault();// 创建Httpclient对象
CloseableHttpResponse response = httpclient.execute(httpPost);// 执行请求
) {
logger.info("httpPost:{}", httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity(), chaset);
logger.info("HttpPost方式请求成功!返回结果:{}", result);
} else {
logger.info("HttpPost方式请求失败!状态码:" + statusCode);
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 发通过url下载视频
*
* @param url
* @return
*/
public static String downVideo(String url) {
//默认下载到D:\video\
return downVideo(url, "D:\\video\\");
}
/**
* 发通过url下载视频
*
* @param url
* @param filepath 下载到本地的路径
* @return
*/
public static String downVideo(String url, String filepath) {
String filename="";
try {
//获取视频流
HttpClient client = HttpClients.createDefault();
HttpGet httpget = new HttpGet(url);
HttpResponse response = client.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
//filepath不是斜杠结束的在末尾添加斜杠
if (filepath.length()-1!=filepath.lastIndexOf("\\")){
filepath+="\\";
}
//如果没有文件夹,则创建
File file = new File(filepath);
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
//获取文件夹下的文件数量,文件数量加一作为要下载的文件名
int fileCount = 0;
File[] list = file.listFiles();
for (int i = 0; i < list.length; i++) {
if (list[i].isFile()) {
fileCount++;
}
}
fileCount += 1;
//如果文件不存在则创建文件
filename = filepath + fileCount + ".mp4";
File file_name = new File(filename);
if (!file_name.exists()) {
//创建文件
file_name.createNewFile();
}
//视频流写入文件
FileOutputStream fileout = new FileOutputStream(file_name);
BufferedInputStream buf = new BufferedInputStream(is);
byte[] buffer = new byte[1024];
int ch = 0;
while ((ch = buf.read(buffer)) != -1) {
fileout.write(buffer, 0, ch);
}
is.close();
fileout.flush();
fileout.close();
} catch (Exception e) {
e.printStackTrace();
}
return "下载成功,文件名:"+filename;
}
}
Just call it directly when used, such as:
Map<String, Object> map = new HashMap<>();
map.put("a", additionModel.getA());
map.put("b", additionModel.getB());
String result = HttpUtil.doGet("http://125.113.27.170:8080/query/v1/addition",map);