赞
踩
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
这里分享一下我对接遇到的奇奇怪怪的请求。超全万能工具类,帮助和我一样第一次接触三方的新手。
先放一个基础的模板。将情况放到指定位置即可,
package com.xxx.utils;
import org.apache.commons.io.IOUtils;
import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
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.HttpClientUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.Map.Entry;
/**
* @author zyx
* @date 2023/3/3 14:23
*/
public class HttpUtil {
private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
private static PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();
private static RequestConfig requestConfig;
public HttpUtil() {
}
/**
* 情况方法直接放这里就行
*/
static {
connMgr.setMaxTotal(100);
connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
Builder configBuilder = RequestConfig.custom();
configBuilder.setConnectTimeout(60000);
configBuilder.setSocketTimeout(70000);
configBuilder.setConnectionRequestTimeout(30000);
requestConfig = configBuilder.build();
}
}
先以发送POST方式
情况1:请求方式POST,请求体JSON
示例如下:
/**
* post,以 application/json 形式
* @param apiUrl
* @param json
* @return
*/
public static String doPost(String apiUrl, String json) {
long start = System.currentTimeMillis();
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
int statusCode = -999;
try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
statusCode = response.getStatusLine().getStatusCode();
httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (Exception var20) {
logger.info("HttpUtil post error:" + var20.getMessage());
var20.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException var19) {
var19.printStackTrace();
}
}
logger.info("request to:{},param:{},response code:{},result:{},cost {} ms", new Object[]{apiUrl, json, statusCode, httpStr, System.currentTimeMillis() - start});
}
return httpStr;
}
情况2:发送方式POST,请求体JSON。携带请求头
postman示例如下
/**
* Post方式
* @param apiUrl
* @param json json数据
* @param headerMap 请求头
* @return
*/
public static String doPost(String apiUrl, String json, Map<String,String> headerMap) {
long start = System.currentTimeMillis();
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
int statusCode = -999;
try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");
stringEntity.setContentEncoding("UTF-8");
//循环增加header
if (headerMap != null) {
Iterator headerIterator = headerMap.entrySet().iterator();
while(headerIterator.hasNext()){
Entry<String,String> elem = (Entry<String, String>) headerIterator.next();
httpPost.addHeader(elem.getKey(),elem.getValue());
}
}
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
statusCode = response.getStatusLine().getStatusCode();
httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (Exception var20) {
logger.info("HttpUtil post error:" + var20.getMessage());
var20.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException var19) {
var19.printStackTrace();
}
}
logger.info("request to:{},param:{},response code:{},result:{},cost {} ms", new Object[]{apiUrl, json, statusCode, httpStr, System.currentTimeMillis() - start});
}
return httpStr;
}
情况3:发送方式POST。请求体表单
/**
* Post请求
* @param apiUrl 请求链接
* @param params 请求类型:x-www-form-urlencoded
* @return
*/
public static String doPost(String apiUrl, Map<String, Object> params) {
long start = System.currentTimeMillis();
CloseableHttpResponse response = null;
String httpStr = null;
int statusCode = -999;
//创建http实例
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建httpPost实例
HttpPost httpPost = new HttpPost(apiUrl);
try {
httpPost.setConfig(requestConfig);
List<NameValuePair> pairList = new ArrayList();
Iterator i$ = params.entrySet().iterator();
while(i$.hasNext()) {
Entry<String, Object> entry = (Entry)i$.next();
NameValuePair pair = new BasicNameValuePair((String)entry.getKey(), entry.getValue().toString());
pairList.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
response = httpClient.execute(httpPost);
statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
logger.info("HttpUtil发生错误:" + e.getMessage());
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
logger.info("request path:{}, param:{},response code:{},result:{},cost {} ms", new Object[]{apiUrl, params.toString(), statusCode, httpStr, System.currentTimeMillis() - start});
}
return httpStr;
}
情况4:最为复杂的,发送方式POST。请求头+表单形式发送请求体+文件。
postman如下:
上传文件,我的情况是,我这个报告文件,在数据库有url。并且已经传到公司文件服务器。对接第三方,现在要把服务器对应url转成文件,上传第三方。
url:http://ip:端口/xxx/2023/03/01/e4d3db2f7d2b4a2b98031192cb590c0c.pdf
先把url的pdf转MultipartFile。
package com.vkl.utils;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
/**
* PDF转换MultipartFile
*
* @author MrLi
* @version 2.0
*/
public class PdfToMultipartFile implements MultipartFile {
private static final String FILENAME_TEMPLATE = "%s.%s";
private final byte[] imgContent;
private final String type;
private final String fileName;
private PdfToMultipartFile(byte[] imgContent, String fileName) {
this.imgContent = imgContent;
this.fileName = String.format(FILENAME_TEMPLATE, fileName + System.currentTimeMillis(), "pdf");
this.type = "image";
}
@Override
public String getName() {
return fileName;
}
@Override
public String getOriginalFilename() {
return fileName;
}
@Override
public String getContentType() {
return type;
}
@Override
public boolean isEmpty() {
return imgContent == null || imgContent.length == 0;
}
@Override
public long getSize() {
return imgContent.length;
}
@Override
public byte[] getBytes() {
return imgContent;
}
@Override
public InputStream getInputStream() {
return new ByteArrayInputStream(imgContent);
}
@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(dest);
fileOutputStream.write(imgContent);
} finally {
if (fileOutputStream != null) {
fileOutputStream.close();
}
}
}
public static File MultipartFileToFile(MultipartFile file){
File toFile = null;
if("".equals(file) || file.getSize()<=0){
file = null;
}else {
try {
InputStream inputStream = file.getInputStream();
toFile = new File(file.getOriginalFilename());
inputStreamToFile(inputStream,toFile);
} catch (IOException e) {
e.printStackTrace();
}
}
return toFile;
}
private static void inputStreamToFile(InputStream inputStream, File toFile) {
FileOutputStream os = null;
try {
os = new FileOutputStream(toFile);
int byteRead = 0;
byte[] buf = new byte[1024*10];
while ((byteRead=inputStream.read(buf,0,1024))!=-1){
os.write(buf,0,byteRead);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static MultipartFile imageUrlToMultipartFile(String fileName, String imageUrl) {
InputStream fileIs = null;
ByteArrayOutputStream out = null;
try {
if (imageUrl.startsWith("http") || imageUrl.startsWith("https")) {
URL urlObj = new URL(imageUrl);
URLConnection urlConnection = urlObj.openConnection();
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(10000);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
fileIs = urlConnection.getInputStream();
if (fileIs != null) {
out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = fileIs.read(buffer)) > -1) {
out.write(buffer, 0, len);
}
out.flush();
byte[] b = out.toByteArray();
return new PdfToMultipartFile(b, fileName);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileIs != null) {
try {
fileIs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
情况4:方法:
/**
* @param url url链接
* @param headMaps 请求头参数
* @param params 请求体参数
* @param multipartFile 上传文件,可上传单文件或者多文件
* @return
*/
public static String sendMultipartFilePost(String url, Map<String,String> headMaps,
Map<String, Object> params,
Map<String,MultipartFile> multipartFile) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = null;
try {
HttpPost httpPost = new HttpPost(url);
if(headMaps!=null){
//循环增加header
Iterator headerIterator = headMaps.entrySet().iterator();
while(headerIterator.hasNext()){
Map.Entry<String,String> elem = (Map.Entry<String, String>) headerIterator.next();
httpPost.addHeader(elem.getKey(),elem.getValue());
}
}
//文件上传
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(Charset.forName("UTF-8"));
//浏览器兼容
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//解决中文乱码
ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
for (Map.Entry<String, Object> entry : params.entrySet()) {
if(entry.getValue() == null) {
continue;
}
//类似浏览器表单提交
builder.addTextBody(entry.getKey(), entry.getValue().toString(), contentType);
}
if(multipartFile != null){
for (Map.Entry<String, MultipartFile> entry: multipartFile.entrySet()){
if(entry.getValue() == null) {
continue;
}
builder.addBinaryBody(entry.getKey(), entry.getValue().getInputStream(), ContentType.MULTIPART_FORM_DATA, entry.getValue().getOriginalFilename());
}
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
//执行提交
HttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
//将响应内容转换为字符串
result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
logger.info("request to:{},param:{},file:{}", new Object[]{url,params.toString()});
}
return result;
}
发送GET方式
情况1:GET方式,参数
不要直接在代码写死拼装url。参数用map传。动态获取。
/**
* @param url
* @param params 带参数
* @return
*/
public static String doGet(String url, Map<String, Object> params) {
long start = System.currentTimeMillis();
StringBuffer param = new StringBuffer();
int i = 0;
for(Iterator i$ = params.keySet().iterator(); i$.hasNext(); ++i) {
String key = (String)i$.next();
if (i == 0) {
param.append("?");
} else {
param.append("&");
}
param.append(key).append("=").append(params.get(key));
}
String apiUrl = url + param;
String result = null;
//创建一个httpClient
CloseableHttpClient httpClient = HttpClients.createDefault();
int statusCode = -999;
try {
HttpGet httpGet = new HttpGet(apiUrl);
HttpResponse response = httpClient.execute(httpGet);
statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
}
} catch (Exception var18) {
logger.info("httputil get error:" + var18.getMessage());
var18.printStackTrace();
} finally {
if (httpClient != null) {
//关闭流
HttpClientUtils.closeQuietly(httpClient);
}
logger.info("request to:{},param:{},response code:{},result:{},cost {} ms", new Object[]{apiUrl, param.toString(), statusCode, result, System.currentTimeMillis() - start});
}
return result;
}
情况2:GET请求方式,参数+请求头
/**
* 请求方式 Get
* @param url 请求链接
* @param params 以 x-www-form-urlencoded
* @param headerMap 请求头参数
* @return
*/
public static String doGet(String url, Map<String, Object> params, Map<String,String> headerMap) {
long start = System.currentTimeMillis();
StringBuffer param = new StringBuffer();
int i = 0;
for(Iterator i$ = params.keySet().iterator(); i$.hasNext(); ++i) {
String key = (String)i$.next();
if (i == 0) {
param.append("?");
} else {
param.append("&");
}
param.append(key).append("=").append(params.get(key));
}
String apiUrl = url + param;
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
int statusCode = -999;
try {
HttpGet httpGet = new HttpGet(apiUrl);
//循环增加header
if (headerMap != null) {
Iterator headerIterator = headerMap.entrySet().iterator();
while(headerIterator.hasNext()){
Entry<String,String> elem = (Entry<String, String>) headerIterator.next();
httpGet.addHeader(elem.getKey(),elem.getValue());
}
}
HttpResponse response = httpClient.execute(httpGet);
statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
}
} catch (Exception e) {
logger.info("HttpUtil发生错误:" + e.getMessage());
e.printStackTrace();
} finally {
if (httpClient != null) {
HttpClientUtils.closeQuietly(httpClient);
}
logger.info("request to:{},param:{},response code:{},result:{},cost {} ms", new Object[]{apiUrl, param.toString(), statusCode, result, System.currentTimeMillis() - start});
}
return result;
}
觉得对你有帮助,点赞收藏一波
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。