java - Spring RestTemplate:多部分/表单数据禁止获取 403,但使用 curl
问题描述
我正在使用 spring rest-template 来form-data
发布 1 个文件和 1 个字符串参数的请求,这里是代码:
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer ...");
httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
File file=new File("src\main\resources\test.json");
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
byte[] fileBytes = toByteArray(in);
MultiValueMap<String, String> fileMap = new LinkedMultiValueMap<>();
ContentDisposition contentDisposition = ContentDisposition
.builder("form-data")
.name("file")
.filename("test.json")
.build();
fileMap.add(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());
fileMap.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
org.springframework.http.HttpEntity<byte[]> fileEntity =
new org.springframework.http.HttpEntity<>(fileBytes, fileMap);
MultiValueMap< String, Object > body = new LinkedMultiValueMap<>();
body.add("stringFormInput", "xyz");
body.add("file", fileEntity);
org.springframework.http.HttpEntity< MultiValueMap< String, Object > > entity =
new org.springframework.http.HttpEntity<>(body, httpHeaders);
ResponseEntity< JsonNode > responseEntity =
restTemplate.postForEntity("https://uploadFile", entity, JsonNode.class);
但我得到了403 FORBIDDEN
回应
但是,如果我使用下面的 curl 命令,它会成功执行
curl --location --request POST 'https://uploadFile' \
--header 'Content-Type: multipart/form-data' \
--header 'Authorization: Bearer ...' \
--form 'file=@/D:/resources/test.json' \
--form 'stringFormInput=xyz' \
我也试过了httpClient
,仍然是 403,没有任何原因消息
HttpPost post = new HttpPost("https://uploadFile");
post.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE);
post.setHeader(HttpHeaders.AUTHORIZATION, "Bearer ...");
File file=new File("src\main\resources\test.json");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, "test.json");
builder.addTextBody("stringFormInput", "xyz", ContentType.DEFAULT_BINARY);
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse response = httpClient.execute(post);
编辑
现在我通过从JAVA执行curl做了一个解决方法
File file=new File("src\main\resources\test.json");
String[] command = {"curl", "--location",
"--request", "POST", "https://uploadFile",
"--header", "Content-Type: multipart/form-data",
"--header", "Authorization: Bearer ...",
"-F", "file=" + "@"+file.getPath(),
"--form", "stringFormInput=xyz"};
ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
String curlResult = "";
String line = "";
try {
Process process = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(process.getInputStream()));
while (true) {
line = r.readLine();
if (line == null) {
break;
}
curlResult = curlResult + line;
}
} catch (Exception e) {
e.printStackTrace();
}
解决方案
所以我遇到了一个类似的问题,即 cURL 执行正确,但 Spring 代码给出了 403。问题在于接收此请求的目标。很少有像 Nginx 这样的 Web 服务器默认需要像“User-Agent”这样的强制标头,可以禁用。
默认情况下,Spring 不传递任何额外的标头。如果目标正在使用 Ngnix,请尝试添加“User-Agent”或查找他们正在使用的 Web 服务器。
分享我的代码以供参考。
此代码给出了 403
HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
这段代码运行良好。
HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA); httpHeaders.add("用户代理", "PostmanRuntime/7.26.3");
推荐阅读
- url - 如果用户在浏览器中更改 url 并且请求无效留在 yii2 中的当前页面
- javascript - Google recaptcha V3 检查分数
- ansible - 如何在 Ansible / Jinja2 中获取变量的插值
- python - 奇怪的错误 - 数据存储系统 Discord.py 重写
- java - Java 正则表达式:自定义 URL
- android - ConscryptEngine 数据读取问题:无法解析 TLS 数据包标头
- docker - 无法使用 System.InvalidOperationException 启动 Kestrel:无法配置 HTTPS 端点
- ruby - 实例变量不在方法之间共享
- jquery - 如何在事件侦听器中覆盖事件阻止默认值?
- javascript - for循环向jQuery中的多个输入字段添加点击功能没有按预期工作