首先,我问了这个问题What did I miss to send a http part post request,似乎我不理解从客户端向服务器发送multipart的逻辑。使用这篇文章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);
我的问题是在服务器中,我一直收到零件的数量为零。对于某些服务器没有收到部件的人(注意我并不是说服务器中有例外)
我这样说是因为在服务器(我的servlet)上我这样做
Iterator<Part> partsIterator = request.getParts().iterator();
System.out.println("The number of parts is :"
+ request.getParts().size());
并且打印结果始终为零,始终为
我错过了什么?
答案 0 :(得分:1)
的Servlet&#39; multipart配置需要Content-Type
multipart/form-data
。
这是在javadoc of @MultipartConfig
可以在
javax.servlet.Servlet
类上指定的注释, 指示Servlet
的实例期望符合要求的请求 到multipart/form-data
MIME类型。
您正在指定其他内容类型
httpPost.addHeader("Content-Type", "multipart/related; boundary=HereItGoes");
摆脱这个。 MultipartEntityBuilder
已使用适当的标头构建请求。只需添加
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个部分,并附有您问题中的代码。