从ApacheHTTP客户端执行多部件请求时,HTTP 400

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (146)

我正在尝试将来自Servlet的请求转发到在tomcat 7上运行的JAX-RS的CXF实现中实现的实际后端。

以下是我的代码,

protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
    HttpPost postRequest = new HttpPost(targetURL);
    if (ServletFileUpload.isMultipartContent(req)) {
        ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
        List<FileItem> fileItemList = servletFileUpload.parseRequest(req);
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        for (FileItem item: fileItemList) {
            entityBuilder.addPart(item.getFieldName(), new ByteArrayBody(item.get(), ContentType.create(item.getContentType()), item.getName()));
        }
        postRequest.setEntity(entityBuilder.build());
    } else {
        if (StringUtils.isNotEmpty(req.getHeader(HttpHeaders.CONTENT_LENGTH)) || StringUtils.isNotEmpty(req.getHeader(HttpHeaders.TRANSFER_ENCODING))) {
            InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), Long.parseLong(req.getHeader(HttpHeaders.CONTENT_LENGTH)));
            postRequest.setEntity(entity);
        }
    }
    postRequest.setHeader(postRequest.getEntity().getContentType());
    postRequest.setHeader(HttpHeaders.AUTHORIZATION, "ACCESS-TOKEN");
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpResponse response = client.execute(httpRequest);
    }
}

上面的代码运行没有非多部分请求的问题。但是,每当我尝试多部分请求时,都会收到“HTTP 400 Bad Request”响应。请求也没有传递给实际的实现(后端没有错误)

我试图保留传入的内容类型标头与原始边界,然后后端抛出以下错误。

Caused by: org.apache.cxf.interceptor.Fault: Couldn't find MIME boundary: ----------------------------282428552532940822247758
at org.apache.cxf.interceptor.AttachmentInInterceptor.handleMessage(AttachmentInInterceptor.java:60)
at org.apache.cxf.jaxrs.ext.MessageContextImpl.createAttachments(MessageContextImpl.java:268)
at org.apache.cxf.jaxrs.ext.MessageContextImpl.get(MessageContextImpl.java:77)

不知道我在这里做错了什么?

提问于
用户回答回答于
postRequest.setHeader(postRequest.getEntity().getContentType());

不要那样做。HttpClient Content-Type根据所包含的属性自动为请求消息体生成标头HttpEntity

扫码关注云+社区

领取腾讯云代金券