更新时间:2022-11-23 08:57:21 来源:极悦 浏览2088次
通过
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
生成HttpEntity,然后再设置到HttpPost中。具体实现如下
httpPostForm
/**
* 模拟from表单提交
*
* @param url url地址
* @param paramList 参数
* @param headers 请求头
* @return
*/
public static JSONObject httpPostForm(String url, HttpEntity httpEntity , Map<String, String> headers) {
// post请求返回结果
CloseableHttpClient httpClient = HttpClients.createDefault();
JSONObject jsonResult = null;
HttpPost httpPost = new HttpPost(url);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(10000).setConnectTimeout(10000).build();
httpPost.setConfig(requestConfig);
if (!headers.isEmpty()) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
try {
if (null != paramList ) {
// 解决中文乱码问题
httpPost.setEntity(paramList);
}
CloseableHttpResponse result = httpClient.execute(httpPost);
String resultString = EntityUtils.toString(result.getEntity(), "utf-8");
logger.info(result);
//请求发送成功,并得到响应
try {
//把json字符串转换成json对象
jsonResult = JSONObject.parseObject(resultString);
} catch (Exception e) {
logger.error("post请求提交失败:" + url, e);
}
} catch (IOException e) {
logger.error("post请求提交失败:" + url, e);
} finally {
httpPost.releaseConnection();
}
return jsonResult;
}
参数调用方式
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
//当需要传入list结构的表单数据的时候直接重名即可,如下面的“to”
multipartEntityBuilder.addPart("to", new StringBody("A", ContentType.TEXT_PLAIN));
multipartEntityBuilder.addPart("to", new StringBody("B", ContentType.TEXT_PLAIN));
multipartEntityBuilder.addPart("cc", new StringBody("C", ContentType.TEXT_PLAIN));
HttpEntity build = multipartEntityBuilder.build();
JSONObject jsonObject = HttpUtil.httpPostForm( "www.baidu.com", build, header);
0基础 0学费 15天面授
Java就业班有基础 直达就业
业余时间 高薪转行
Java在职加薪班工作1~3年,加薪神器
工作3~5年,晋升架构
提交申请后,顾问老师会电话与您沟通安排学习