簡體   English   中英

Spring RestTemplate:多部分/表單數據禁止獲取 403,但使用 curl

[英]Spring RestTemplate: getting 403 forbidden for multipart/form-data but working with curl

我正在使用 spring rest-template 來發布 1 個文件和 1 個字符串參數的請求form-data ,這里是代碼:

    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 不會傳遞任何額外的 header。 如果目標正在使用 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");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM