【发布时间】:2021-02-02 11:23:42
【问题描述】:
我在 java 中发出一个 post 请求并得到 400 作为响应代码。但是在 Postman 中构造相同的请求会得到 200.
这是我用于发出请求的 Java 代码:-
final URI baseUri = new URIBuilder("localhost:8080/api/service?ask=true&uid=user&pp=secret").build();
final URIBuilder applicationUriBuilder = new URIBuilder(baseUri);
URI applicationURI = applicationUriBuilder.build();
HttpPost httpPost = new HttpPost(applicationURI);
File resumeFile = resourceLoader.getResource("classpath:/data/2655386.docx").getFile();
StringBody userDetailsString = new StringBody(objectMapper.writeValueAsString(userProfileDetails), MULTIPART_FORM_DATA);
FileBody fileBody = new FileBody(resumeFile, DEFAULT_BINARY);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.addPart("props",userDetailsString);
entityBuilder.addPart("file",fileBody);
entityBuilder.addTextBody("contentField","CONTENT");
HttpEntity entity = entityBuilder.build();
httpPost.setEntity(entity);
httpPost.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE);
httpPost.addHeader(HttpHeaders.ACCEPT,"*/*");
CloseableHttpResponse httpResponse = httpClient.execute(httpPost))
String json = EntityUtils.toString(httpResponse.getEntity());
我收到此错误
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Error 400 Bad Request</title>
</head>
<body><h2>HTTP ERROR 400</h2>
<p>Problem accessing localhost:8080/api/service?ask=true&uid=user&pp=secret. Reason:
<pre> Bad Request</pre></p><hr><i><small>Powered by Jetty://</small></i><hr/>
</body>
</html>
有人可以建议代码有什么问题吗?提前致谢
【问题讨论】:
-
也许“内容类型”(MIME 类型)不匹配会引发此错误。 Postman 不会阻止此问题,但浏览器对“内容类型”问题非常严格。你能分享 Postman 的“标题”标签图片吗?
-
标题在邮递员中是空白的,如您在图像中看到的。但是在 curl 请求标头中是 -H 'cache-control: no-cache' \ -H 'content-type: multipart/form-data;边界=----WebKitFormBoundary7MA4YWxkTrZu0gW' \ -H '邮递员令牌:333231ef-55ee-c6b3-73fa-6eb21e454685' \
-
@Md.KawserHabib 你是对的,这是由于内容类型不匹配而发生的。当我添加 content-type: "/" 时,它起作用了。对此有何解释?
-
我在回答部分写了详细的解释。
标签: java spring-boot http-post