先说下背景:我最近负责的项目,需要调用第三方接口,发送 get/post/put/delete 请求,这些请求有的需要经过 digest 认证,有的则不需要进行 digest 认证,直接请求就可以了 get 请求还好说一些,直接使用 hutool 工具类中的 get 请求就可以满足需要,那你可能会说, hutool 工具类也支持 post 请求呀,但是如果我的 post 请求需要以 form-data 形式提交,它就不满足了,而且 hutool 工具类也不支持发送 put/delete 请求
所以我就自己写了个工具类,不过我写的这个比较粗糙,放在这里,有需要的人看着拿吧~回头我有时间的话,就再优化一下:
public class HttpUtils {
public static String doPostFormData(String url, String fileParamName, MultipartFile multipartFile, Map<String, String> paramMap) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000)
.setConnectionRequestTimeout(10000).build();
httpPost.setConfig(requestConfig);
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create()
.setCharset(Consts.UTF_8);
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.setContentType(ContentType.MULTIPART_FORM_DATA);
builder.setCharset(StandardCharsets.UTF_8);
FormBodyPart part = FormBodyPartBuilder.create()
.setName(fileParamName)
.setBody(new ByteArrayBody(
multipartFile.getBytes(),
ContentType.create(multipartFile.getContentType(), StandardCharsets.UTF_8),
multipartFile.getOriginalFilename()))
.build();
builder.addPart(part);
if(paramMap != null) {
for (Map.Entry<String, String> entry : paramMap.entrySet()) {
builder.addPart(FormBodyPartBuilder.create()
.setName(entry.getKey())
.setBody(new StringBody(entry.getValue(),
ContentType.create(
ContentType.TEXT_PLAIN.getMimeType(),
StandardCharsets.UTF_8)))
.build());
}
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String res = EntityUtils.toString(response.getEntity(), java.nio.charset.Charset.forName("UTF-8"));
return res;
}else {
HttpEntity responseEntity = response.getEntity();
byte[] msg = new byte[(int) responseEntity.getContentLength()];
responseEntity.getContent().read(msg);
log.error("error msg: {}", new String(msg));
}
} catch (Exception e) {
e.printStackTrace();
log.error("调用 HttpPost 失败!" + e.toString());
} finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
log.error("关闭 HttpPost 连接失败!");
}
}
}
return null;
}
public static String doDelete(JSONObject dataMap, String url, Boolean flag){
CloseableHttpClient client = null;
if(flag){
client = digestHttpClient(null,null);
}else {
client = HttpClients.createDefault();
}
HttpDeleteWithBodyUtil httpDelete = null;
String result = null;
try {
httpDelete = new HttpDeleteWithBodyUtil(url);
httpDelete.addHeader("Content-type","application/json; charset=utf-8");
httpDelete.setHeader("Accept", "application/json; charset=utf-8");
if (dataMap != null){
StringEntity stringEntity = new StringEntity(dataMap.toJSONString(),"UTF-8");
httpDelete.setEntity(stringEntity);
}
CloseableHttpResponse response = client.execute(httpDelete);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String res = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
return res;
} else {
HttpEntity responseEntity = response.getEntity();
byte[] msg = new byte[(int) responseEntity.getContentLength()];
responseEntity.getContent().read(msg);
JSONObject parse = JSONObject.parseObject(new String(msg));
log.error("error msg: {}", parse);
}
} catch (Exception e) {
log.error("发送 http delete 请求时出现错误,请求路径: {} ,错误信息: {}",url, e.toString());
} finally {
if (client != null) {
try {
client.close();
} catch (IOException e) {
log.error("关闭 HttpPost 连接失败!");
}
}
}
return null;
}
public static String doPut(JSONObject dataMap, String url, Boolean flag){
CloseableHttpClient client = null;
if(flag){
client = digestHttpClient(null,null);
}else {
client = HttpClients.createDefault();
}
String result = null;
try {
HttpPut httpPut = new HttpPut(url);
httpPut.addHeader("Content-Type", "application/json");
if (dataMap != null) {
StringEntity stringEntity = new StringEntity(dataMap.toJSONString());
httpPut.setEntity(stringEntity);
}
HttpResponse response = client.execute(httpPut);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String res = EntityUtils.toString(response.getEntity(), java.nio.charset.Charset.forName("UTF-8"));
return res;
}else {
HttpEntity responseEntity = response.getEntity();
byte[] msg = new byte[(int) responseEntity.getContentLength()];
responseEntity.getContent().read(msg);
JSONObject parse = JSONObject.parseObject(new String(msg));
log.error("error msg: {}", new String(msg));
}
} catch (Exception e) {
log.error("发送 http put 请求时出现错误,请求路径: {} ,错误信息: {}",url, e.toString());
} finally {
if (client != null) {
try {
client.close();
} catch (IOException e) {
log.error("关闭 HttpPut 连接失败!");
}
}
}
return null;
}
public static String doPost(JSONObject dataMap, String url, Boolean flag){
CloseableHttpClient client = null;
if(flag){
client = digestHttpClient(null,null);
}else {
client = HttpClients.createDefault();
}
String result = null;
try {
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json");
if (dataMap != null) {
StringEntity s = new StringEntity(dataMap.toString(),"UTF-8");
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
httpPost.setEntity(s);
}
HttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String res = EntityUtils.toString(response.getEntity(), java.nio.charset.Charset.forName("UTF-8"));
return res;
} else {
HttpEntity entity = response.getEntity();
byte[] msg = new byte[(int) entity.getContentLength()];
entity.getContent().read(msg);
JSONObject parse = JSONObject.parseObject(new String(msg));
log.error("error msg: {}", parse);
}
} catch (Exception e) {
log.error("发送 http post 请求时出现错误,请求路径: {} ,错误信息: {}",url, e.toString());
} finally {
if (client != null) {
try {
client.close();
} catch (IOException e) {
log.error("关闭 HttpPost 连接失败!");
}
}
}
return null;
}
public static String doPostFormDataByArray(String url, String fileParamName, MultipartFile multipartFile, Map<String, Object> paramMap) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000)
.setConnectionRequestTimeout(10000).build();
httpPost.setConfig(requestConfig);
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create()
.setCharset(Consts.UTF_8);
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.setContentType(ContentType.MULTIPART_FORM_DATA);
builder.setCharset(StandardCharsets.UTF_8);
FormBodyPart part = FormBodyPartBuilder.create()
.setName(fileParamName)
.setBody(new ByteArrayBody(
multipartFile.getBytes(),
ContentType.create(multipartFile.getContentType(), StandardCharsets.UTF_8),
multipartFile.getOriginalFilename()))
.build();
builder.addPart(part);
if(paramMap != null) {
for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
String name = entry.getKey();
Object value = entry.getValue();
builder.addPart(FormBodyPartBuilder.create()
.setName(name)
.setBody(new StringBody(value.toString(),
ContentType.create(
ContentType.TEXT_PLAIN.getMimeType(),
StandardCharsets.UTF_8)))
.build());
}
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String res = EntityUtils.toString(response.getEntity(), java.nio.charset.Charset.forName("UTF-8"));
return res;
} else {
HttpEntity responseEntity = response.getEntity();
byte[] msg = new byte[(int) responseEntity.getContentLength()];
responseEntity.getContent().read(msg);
JSONObject parse = JSONObject.parseObject(new String(msg));
log.error("error msg: {}", parse);
}
} catch (Exception e) {
e.printStackTrace();
log.error("调用 HttpPost 失败!" + e.toString());
} finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
log.error("关闭 HttpPost 连接失败!");
}
}
}
return null;
}
public static CloseableHttpClient digestHttpClient(String host, Integer port){
String username = UserUtils.username;
String password = UserUtils.password;
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(StringUtils.isEmpty(host) ? AuthScope.ANY_HOST : host, port == null ? AuthScope.ANY_PORT : port),
new UsernamePasswordCredentials(username,password));
return HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
}
public class HttpDeleteWithBodyUtil extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME = "DELETE";
@Override
public String getMethod() {
return METHOD_NAME;
}
public HttpDeleteWithBodyUtil(final String uri) {
super();
setURI(URI.create(uri));
}
public HttpDeleteWithBodyUtil(final URI uri) {
super();
setURI(uri);
}
public HttpDeleteWithBodyUtil() {
super();
}
}
我刚刚在看资料的时候,发现还有 okhttpclient 和 restTemplate ,感兴趣的小伙伴也可以看看这块~ 以上,感谢您的阅读哇
|