gpt4 book ai didi

Java servlet 无法接收 http post 多部分请求的各个部分

转载 作者:行者123 更新时间:2023-11-30 07:56:03 25 4
gpt4 key购买 nike

首先,我问了这个问题What did I miss to send a http part post request看来我不理解从客户端发送多部分到服务器的逻辑。使用这篇文章https://developer.constantcontact.com/docs/mylibrary-files-api/file-add-multipart-post.html我无法看到每个部分中的必填字段。

我构建了我的请求并添加了所有必填字段,如您在此处看到的

HttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(
"http://localhost:8080/ServletExample1/multipart1");
httpPost.addHeader("Content-Type",
"multipart/related; boundary=HereItGoes");
httpPost.addHeader("Accept", MediaType.TEXT_PLAIN);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
FileBody bin = new FileBody(new File("./test.txt"));
builder.addPart("source", new StringBody("MyComputer",
ContentType.TEXT_PLAIN));
builder.addPart("folder_id", new StringBody("-1",
ContentType.TEXT_PLAIN));
builder.addPart("file_type", new StringBody("txt",
ContentType.TEXT_PLAIN));
builder.addPart("file_name", new StringBody("test.txt",
ContentType.TEXT_PLAIN));
builder.addPart("description", new StringBody("The file to test",
ContentType.TEXT_PLAIN));
builder.addPart("data", bin);
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = client.execute(httpPost);
String responseString = new BasicResponseHandler()
.handleResponse(response);
System.out.println(responseString);

我的问题出在服务器上,我不断收到零件数量为零的信息。对于某些人来说,服务器没有收到零件(注意我并不是说服务器中有异常(exception))

我这么说是因为在服务器(我的 servlet)上我这样做

Iterator<Part> partsIterator = request.getParts().iterator();
System.out.println("The number of parts is :"
+ request.getParts().size());

并且打印结果始终为零,始终

请问我缺少什么?

最佳答案

Servlet 的多部分配置需要 Content-Typemultipart/form-data

这是在 javadoc of @MultipartConfig 等地方指定的。

Annotation that may be specified on a javax.servlet.Servlet class, indicating that instances of the Servlet expect requests that conform to the multipart/form-data MIME type.

您正在指定不同的内容类型

httpPost.addHeader("Content-Type", "multipart/related; boundary=HereItGoes");

摆脱这个。 MultipartEntityBuilder 已经使用适当的 header 构建了一个请求。只需添加

builder.setBoundary("HereItGoes")

边界。

示例Servlet

@WebServlet(loadOnStartup = 1, urlPatterns = "/multipart1")
@MultipartConfig()
public class MyServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("The number of parts is :" + request.getParts().size());
Iterator<Part> partsIterator = request.getParts().iterator();
while (partsIterator.hasNext()) {
System.out.println(partsIterator.next().getName());
}
}
}

它将收到您发送的所有 6 个部分以及问题中的代码。

关于Java servlet 无法接收 http post 多部分请求的各个部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32656760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com