Spring RestTemplate:对于多表格数据得到403禁止,但在curl下可以使用

问题描述 投票:1回答:1

我正在使用spring rest-template进行POST请求。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();
    }
java spring multipartform-data resttemplate http-status-code-403
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.