首页 > 解决方案 > 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();
    }

标签: javaspringmultipartform-dataresttemplatehttp-status-code-403

解决方案


所以我遇到了一个类似的问题,即 cURL 执行正确,但 Spring 代码给出了 403。问题在于接收此请求的目标。很少有像 Nginx 这样的 Web 服务器默认需要像“User-Agent”这样的强制标头,可以禁用。

默认情况下,Spring 不传递任何额外的标头。如果目标正在使用 Ngnix,请尝试添加“User-Agent”或查找他们正在使用的 Web 服务器。

分享我的代码以供参考。

  1. 此代码给出了 403

    HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);

  2. 这段代码运行良好。

    HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA); httpHeaders.add("用户代理", "PostmanRuntime/7.26.3");


推荐阅读