httpclient模拟postman发送请求?
问题描述
post方法调用远端接口,postman成功,自己通过java代码使用httpclient请求失败.
服务端不能够调试,不知道自己的错误 A server error occurred. Please contact the administrator
问题出现的环境背景及自己尝试过哪些方法
- 首先需要将multipartfile转换为file
- 构造的httpclient的entity中,使用的是MultipartEntity
相关代码
// 请把代码文本粘贴到下方(请勿用图片代替代码)
使用postman请求
postman构造请求成功
使用postman请求本地项目
header中设置了content-type 为form-data , 返回值为"A server error occurred. Please contact the administrator."
controller层
@RequestMapping(value = "/image", method = {RequestMethod.POST})
@ResponseBody
public String getSimilarImage( int num, MultipartFile image) {
HashMap<String, String> params = new HashMap<>();
params.put(ConstantUtil.NUM, String.valueOf(num));
String result = null;
File file = null;
try {
// 类型转换使用
file = new File(image.getOriginalFilename());
FileUtils.copyInputStreamToFile(image.getInputStream(),file);
result = HttpClientUtil.doFilePost(gunsProperties.getSimilarImage(), file, params);
System.out.println(result);
} catch (Exception e) {
logger.debug(e.getMessage());
}
File del = new File(file.toURI());
del.delete();
return result;
}
httpclient的工具类post方法
public static String doFilePost(String url, File file, HashMap<String, String> params) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String resultString = "";
try {
httpClient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().
setConnectTimeout(2000000000).
setConnectionRequestTimeout(2000000000).
setSocketTimeout(2000000000).build();
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader(ConstantUtil.CONTENT_TYPE, ConstantUtil.CONTENT_TYPE_VALUE);
httpPost.setConfig(requestConfig);
/*httpPost.setProtocolVersion(HttpVersion.HTTP_1_0);
httpPost.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);*/
// 设置Header信息
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("image", new FileBody(file));
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
StringBody contentBody = new StringBody(entry.getValue(),
"text/plain", Charset.forName("UTF-8"));
builder.addPart(entry.getKey(), contentBody);
}
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
resultString = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
}
} catch (Exception e) {
logger.debug("超时异常,异常为{},异常信息为{}", e, e.getMessage());
MsgResponse.failMessage(ConstantUtil.OUT_OF_DATE);
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
return resultString;
}
你期待的结果是什么?实际看到的错误信息又是什么?
期待和postman一样的结果,不知道中间哪个环节设置错误
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
原因是post中不能设置header,使用multipartfile的时候,已经默认进行了使用