MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);解决了文件名中文乱码
public class HttpUtils {
private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);
public static final String ENCODE = "UTF-8";
/**
* 建立链接
*/
private static final int CONNECT_TIME_OUT = 5 * 1000;
/**
* 读取时间
*/
private static final int SOCKET_TIME_OUT = 10 * 1000;
private static CloseableHttpClient getClient() {
CloseableHttpClient client = HttpClients.createDefault();
return client;
}
private static RequestConfig getRequestConfig(int socketTimeout, int connectTimeout) {
return RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
}
private static RequestConfig getRequestConfig() {
return getRequestConfig(SOCKET_TIME_OUT, CONNECT_TIME_OUT);
}
public static JSONObject postFileForm(String url, Map<String, Object> params, Map<String, File> map) {
logger.debug("postFormJson request url==>{} postData==>{}", url, (null != params ? params.toString() : null));
CloseableHttpClient httpClient = getClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(getRequestConfig());
MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
if (params != null) {
for (String key : params.keySet()) {
builder.addTextBody(key, params.get(key).toString());
}
}
for (String key : map.keySet()) {
builder.addBinaryBody("file", map.get(key), ContentType.DEFAULT_BINARY, key);
}
builder.setContentType(ContentType.create("multipart/form-data", Consts.UTF_8));
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
try {
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity, "UTF-8");
logger.debug("postJson url==>{} response data==>{}", url, content);
EntityUtils.consume(entity);
httpClient.close();
return JSON.parseObject(content);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("post url=>" + url + " error=>" + e.getMessage());
}
}
/**
* 发送 post 请求
*
* @param url
* @param params 写入到entity中
* @return
*/
public static JSONObject postJson(String url, JSONObject params) {
logger.debug("postJson url==>{} post==>{}", url, (null != params ? params.toString() : null));
CloseableHttpClient httpClient = getClient();
HttpPost request = new HttpPost(url);
request.setConfig(getRequestConfig());
request.addHeader("content-type", "application/json; charset=utf-8");
try {
if (null != params && 0 < params.size()) {
StringEntity stringEntity = new StringEntity(params.toJSONString(), ENCODE);
request.setEntity(stringEntity);
}
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity, "UTF-8");
logger.debug("postJson url==>{} response data==>{}", url, content);
EntityUtils.consume(entity);
httpClient.close();
return JSON.parseObject(content);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("post url=>" + url + " error=>" + e.getMessage());
}
}
/**
* 发送 form-data 对象
*
* @param url
* @param params 参数
* @return
*/
public static JSONObject postFormData(String url, Map<String, Object> params) {
logger.debug("postFormJson request url==>{} postData==>{}", url, (null != params ? params.toString() : null));
CloseableHttpClient httpClient = getClient();
CloseableHttpResponse response = null;
HttpPost request = new HttpPost(url);
request.setConfig(getRequestConfig());
List<NameValuePair> postParams = buildPostParam(params);
try {
request.setEntity(new UrlEncodedFormEntity(postParams, ENCODE));
response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity, ENCODE);
logger.debug("postFormJson url==>{} response data==>{}", url, content);
EntityUtils.consume(entity);
return JSON.parseObject(content);
} catch (Exception e) {
logger.error("postFormJson error==>{}", url, e);
throw new ValidatorException(e.getMessage());
} finally {
try {
httpClient.close();
if (response != null) {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("postFormJson url=>" + url + " error=>" + e.getMessage());
}
}
}
/**
* 构建NameValuePair参数
*
* @param param
* @return
*/
public static List<NameValuePair> buildPostParam(Map<String, Object> param) {
List<NameValuePair> nameValuePairs = new ArrayList<>();
if (param != null) {
for (String key : param.keySet()) {
nameValuePairs.add(new BasicNameValuePair(key, param.get(key).toString()));
}
}
return nameValuePairs;
}
}