如何将设置的“边界”正确地设置为java.net.http.HttpRequest标头

时间:2019-09-09 10:05:42

标签: java java-11

我尝试使用JDK11中的 HttpClient HttpRequest 将Multipart文件发送到服务器:

public static int sendMultipartFile(String uri, Path filePath) {
    HttpClient httpClient =`enter code here` HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_2)
            .build();

    HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(uri))
            .POST(HttpRequest.BodyPublishers.ofFile(filePath))
            .header("Content-Type", "multipart/form-data")
            .setHeader("Boundary", "gc0p4Jq0M2Yt08jU534c0p")
            .build();
    HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
    return response.statusCode();
}

服务器端点:

@PostMapping("/api/logs/throw")
public void handleFileUpload(@RequestParam("logs.7z") MultipartFile file) {
    Path path = Paths.get("/home/terminal_logs/");
    storageService.store(file, path);
}

在服务器端发生以下错误:

  

错误17072-[nio-8081-exec-2]   o.a.c.c.C。[。[。[/]。[dispatcherServlet]:的Servlet.service()   路径[]中的servlet [dispatcherServlet]抛出异常   [请求处理失败;嵌套异常为   org.springframework.web.multipart.MultipartException:无法解析   多部分servlet请求;嵌套的异常是java.io.IOException:   org.apache.tomcat.util.http.fileupload.FileUploadException:   请求被拒绝,因为未找到多部分边界],其中   根本原因

如何正确设置标题以避免此错误?

0 个答案:

没有答案