引入maven依赖
<dependency>
<groupId>org.apache.httpcomponentsgroupId>
<artifactId>httpclientartifactId>
<version>4.5.13version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.75version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.16version>
<scope>providedscope>
dependency>
<dependency>
<groupId>org.apache.httpcomponentsgroupId>
<artifactId>httpmimeartifactId>
<version>4.5.13version>
dependency>
提取发送请求方法
/**
* 发送请求
* @param request 请求 HttpPost/HttpGet
* @return string
* @throws IOException
*/
private static String request(HttpUriRequest request) {
String result = null;
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse response = httpClient.execute(request)
){
log.info("响应状态:" + response.getStatusLine());
HttpEntity httpEntity = response.getEntity();
if(httpEntity != null){
result = EntityUtils.toString(httpEntity, Charset.forName("utf-8"));
log.info("响应内容:" + result);
}
}catch (Exception e){
log.error("发送请求错误",e);
}
return result;
}
/**
* get请求
* @param url url,参数拼接在后面 ?name=val&name1=var1
* @return
*/
public static String doGet(String url){
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(DEFAULT_CONFIG);
return request(httpGet);
}
/**
* get请求设置请求头
* @return
*/
public static String doGet(String url, Map<String,String> header){
if(header == null){
throw new RuntimeException("head is not allowed null");
}
HttpGet httpGet = new HttpGet(url);
//添加header
for (Map.Entry<String, String> e : header.entrySet()) {
httpGet.addHeader(e.getKey(), e.getValue());
}
httpGet.setConfig(DEFAULT_CONFIG);
return request(httpGet);
}
/**
* post请求 form表单方式提交
* @param url url
* @param params 参数
* @param header 请求头
* @return
*/
public static String doPost(String url, List<NameValuePair> params,Map<String,String> header){
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(DEFAULT_CONFIG);
//默认form表单提交,可加可不加
httpPost.setHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
if(params != null){
//参数
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,Charset.forName("utf-8"));
httpPost.setEntity(entity);
}
//设置请求头
addHeader(httpPost,header);
return request(httpPost);
}
/**
* post请求 对象传参 ,key对应对象的字段名
* @param url url
* @param param 参数
* @param header 请求头
* @return
*/
public static String doPost(String url, JSONObject param,Map<String,String> header){
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(DEFAULT_CONFIG);
httpPost.setHeader("Content-Type","application/json; charset=UTF-8");
//设置参数
StringEntity stringEntity = new StringEntity(JSON.toJSONString(param),Charset.forName("utf-8"));
httpPost.setEntity(stringEntity);
//设置请求头
addHeader(httpPost,header);
return request(httpPost);
}
/**
* 文件下载
* @param url 文件url地址
* @param header 请求头
* @param fileName 写入本地的文件名称
*/
public static void downLoadFile(String url,Map<String,String> header,String fileName){
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()){
HttpGet httpGet = new HttpGet(url);
//添加请求头
addHeader(httpGet,header);
try (CloseableHttpResponse response = httpClient.execute(httpGet)){
log.info("响应状态:" + response.getStatusLine());
HttpEntity httpEntity = response.getEntity();
if(httpEntity != null){
//获取输入流
try (InputStream inputStream = httpEntity.getContent()){
Path path = Paths.get(DOWNLOAD_PATH + fileName);
//文件流存入本地目录
Files.copy(inputStream,path);
}
}
}
}catch (Exception e){
log.error("下载文件错误",e);
}
}
/**
* 文件上传
* @param url url
* @param paramName 参数名称
* @param inputStream 文件输入流
* @param fileName 文件名称(上传接口获取到的名称)
* @return
*/
public static String uploadFile(String url,String paramName,InputStream inputStream,String fileName){
try {
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.addBinaryBody(paramName,inputStream, ContentType.DEFAULT_BINARY,fileName);
HttpEntity httpEntity = multipartEntityBuilder.build();
httpPost.setEntity(httpEntity);
return request(httpPost);
}finally {
try {
inputStream.close();
} catch (IOException e) {
log.error("关闭InputStream输入流异常",e);
}
}
}
/**
* 多文件上传
* @param url url
* @param paramName 参数名称
* @param filePath 文件夹目录(将这个文件夹一级子文件都上传)
* @return
*/
public static String uploadFiles(String url,String paramName,String filePath){
File file = new File(filePath);
if(!file.exists() || !file.isDirectory()){
return null;
}
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
for(File f : file.listFiles()){
if(f.isFile()){
multipartEntityBuilder.addBinaryBody(paramName,f, ContentType.DEFAULT_BINARY,f.getName());
}
}
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(multipartEntityBuilder.build());
return request(httpPost);
}
gitee地址:https://gitee.com/zhaoqingquan/httpclient
package com.example.demo.httpclient;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
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.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author zqq
* @date 2021/4/28 17:09
*/
@Slf4j
public class HttpClientUtil {
/**
* 默认配置信息
*/
private static RequestConfig DEFAULT_CONFIG;
private static final String DOWNLOAD_PATH = "D:\\downloadtest\\";
static {
DEFAULT_CONFIG = RequestConfig.custom()
//连接超时时间 毫秒
.setConnectTimeout(5 * 1000)
//请求超时时间 毫秒
.setConnectionRequestTimeout(5 * 1000)
//读写超时时间
.setSocketTimeout(5 * 1000).build();
}
public static void main(String[] args) throws Exception{
Map<String,String> head = new HashMap<>(1,1);
head.put("testhead","head");
String result = null;
//1.get请求测试
//result = doGet("http://127.0.0.1/test/testGet?param=这是参数");
//2.get请求带头测试
//result = doGet("http://127.0.0.1/test/testGet?param=testparam",head);
//3.post请求 form表单提交测试 Content-Type=application/x-www-form-urlencoded; charset=UTF-8
/*List params = new ArrayList<>(2);
params.add(new BasicNameValuePair("name","zqq"));
params.add(new BasicNameValuePair("sex","男"));
result = doPost("http://127.0.0.1/test/testPost",params,head);*/
//4.post请求 传对象测试 "Content-Type","application/json; charset=UTF-8"
/*JSONObject paramJson = new JSONObject();
paramJson.put("name","zqq");
paramJson.put("sex","男");
result = doPost("http://127.0.0.1/test/testPostObject",paramJson,null);*/
//5.下载文件测试
//downLoadFile("http://127.0.0.1/test/downtest",null,"431.png"); //接口下载文件测试
//downLoadFile("https://profile.csdnimg.cn/B/5/9/0_zhaoqingquanajax",null,"head.png"); //下载网络文件测试
//6.上传文件测试
/* File file = new File("D:\\downloadtest\\123.png");
InputStream inputStream = new FileInputStream(file);
result = uploadFile("http://127.0.0.1/test/uploadTest","file",inputStream,file.getName());*/
//7.多文件上传测试
result = uploadFiles("http://127.0.0.1/test/uploadFiles","files","D:\\downloadtest\\");
System.out.println(result);
}
/**
* get请求
* @param url url,参数拼接在后面 ?name=val&name1=var1
* @return
*/
public static String doGet(String url){
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(DEFAULT_CONFIG);
return request(httpGet);
}
/**
* get请求设置请求头
* @return
*/
public static String doGet(String url, Map<String,String> header){
if(header == null){
throw new RuntimeException("head is not allowed null");
}
HttpGet httpGet = new HttpGet(url);
//添加header
for (Map.Entry<String, String> e : header.entrySet()) {
httpGet.addHeader(e.getKey(), e.getValue());
}
httpGet.setConfig(DEFAULT_CONFIG);
return request(httpGet);
}
/**
* 发送请求
* @param request 请求 HttpPost/HttpGet
* @return string
* @throws IOException
*/
private static String request(HttpUriRequest request) {
String result = null;
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse response = httpClient.execute(request)
){
log.info("响应状态:" + response.getStatusLine());
HttpEntity httpEntity = response.getEntity();
if(httpEntity != null){
result = EntityUtils.toString(httpEntity, Charset.forName("utf-8"));
log.info("响应内容:" + result);
}
}catch (Exception e){
log.error("发送请求错误",e);
}
return result;
}
/**
* post请求 form表单方式提交
* @param url url
* @param params 参数
* @param header 请求头
* @return
*/
public static String doPost(String url, List<NameValuePair> params,Map<String,String> header){
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(DEFAULT_CONFIG);
//默认form表单提交,可加可不加
httpPost.setHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
if(params != null){
//参数
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,Charset.forName("utf-8"));
httpPost.setEntity(entity);
}
//设置请求头
addHeader(httpPost,header);
return request(httpPost);
}
/**
* post请求 对象传参 ,key对应对象的字段名
* @param url url
* @param param 参数
* @param header 请求头
* @return
*/
public static String doPost(String url, JSONObject param,Map<String,String> header){
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(DEFAULT_CONFIG);
httpPost.setHeader("Content-Type","application/json; charset=UTF-8");
//设置参数
StringEntity stringEntity = new StringEntity(JSON.toJSONString(param),Charset.forName("utf-8"));
httpPost.setEntity(stringEntity);
//设置请求头
addHeader(httpPost,header);
return request(httpPost);
}
/**
* 添加请求头
* @param httpPost post请求
* @param header 请求头
*/
private static void addHeader(HttpRequestBase httpPost, Map<String,String> header){
if(header == null || header.isEmpty()){
return;
}
//添加header
for (Map.Entry<String, String> e : header.entrySet()) {
httpPost.addHeader(e.getKey(), e.getValue());
}
}
/**
* 文件下载
* @param url 文件url地址
* @param header 请求头
* @param fileName 写入本地的文件名称
*/
public static void downLoadFile(String url,Map<String,String> header,String fileName){
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()){
HttpGet httpGet = new HttpGet(url);
//添加请求头
addHeader(httpGet,header);
try (CloseableHttpResponse response = httpClient.execute(httpGet)){
log.info("响应状态:" + response.getStatusLine());
HttpEntity httpEntity = response.getEntity();
if(httpEntity != null){
//获取输入流
try (InputStream inputStream = httpEntity.getContent()){
Path path = Paths.get(DOWNLOAD_PATH + fileName);
//文件流存入本地目录
Files.copy(inputStream,path);
}
}
}
}catch (Exception e){
log.error("下载文件错误",e);
}
}
/**
* 文件上传
* @param url url
* @param paramName 参数名称
* @param inputStream 文件输入流
* @param fileName 文件名称(上传接口获取到的名称)
* @return
*/
public static String uploadFile(String url,String paramName,InputStream inputStream,String fileName){
try {
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.addBinaryBody(paramName,inputStream, ContentType.DEFAULT_BINARY,fileName);
HttpEntity httpEntity = multipartEntityBuilder.build();
httpPost.setEntity(httpEntity);
return request(httpPost);
}finally {
try {
inputStream.close();
} catch (IOException e) {
log.error("关闭InputStream输入流异常",e);
}
}
}
/**
* 多文件上传
* @param url url
* @param paramName 参数名称
* @param filePath 文件夹目录(将这个文件夹一级子文件都上传)
* @return
*/
public static String uploadFiles(String url,String paramName,String filePath){
File file = new File(filePath);
if(!file.exists() || !file.isDirectory()){
return null;
}
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
for(File f : file.listFiles()){
if(f.isFile()){
multipartEntityBuilder.addBinaryBody(paramName,f, ContentType.DEFAULT_BINARY,f.getName());
}
}
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(multipartEntityBuilder.build());
return request(httpPost);
}
}