java - 在 java 中使用表单数据的 HTTP POST 请求返回 400
问题描述
我在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 不会阻止此问题,但浏览器对“内容类型”问题非常严格。对于文件类型,它将是 multipart/form-data。
Content-Type: multipart/form-data;
降低安全风险浏览器检查请求和响应 MIME 类型。如果它们不匹配,则浏览器/服务器端会阻止内容/内容传递。这是一项安全功能。从浏览器等客户端,您可以停止 MIME 类型检查。对于服务器端也是如此。但它增加了安全风险。
从wiki我们可以找到安全风险的基本概念,
内容嗅探,也称为媒体类型嗅探或MIME 嗅探,是检查字节流内容以尝试推断其中数据的文件格式的做法。内容嗅探通常用于弥补准确元数据的缺乏,否则需要这些元数据才能正确解释文件。内容嗅探技术倾向于使用多种技术,这些技术依赖于大多数文件格式中的冗余:寻找文件签名和幻数,以及启发式方法,包括搜索著名的代表性子字符串、字节频率的使用和 n-gram表和贝叶斯推理。
更多关于 MIME 类型你可以阅读这篇文章。
推荐阅读
- sympy - 如何在 SymPy 中求解包含 Sum 的方程?
- c++ - 第三方库中的宏冲突
- embedded - Coverity 静态分析将 char 或 numbers 视为 C 中的 int
- extjs - 本地网格过滤器
- xml - 如何限制 Excel 加载项的受支持应用程序集以发布到 AppSource?
- css - 如何在 Ruby on Rails (5.2) 中实现页面特定的 CSS
- r - is.list 总是在 tibble 列上返回 true?
- ffmpeg - ffmpeg 每 15 秒下降一次
- amazon-web-services - 当我们在没有 -it 的情况下触发 docker run 命令时如何运行 bash?
- javascript - 尝试以表格形式显示统计信息,不断收到“警告:validateDOMNesting(...):”错误