I am trying to send an image using http multipart request (later I will add another image)
I did this:
HttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(
"http://localhost:8080/ServletExample1/multipart1");
httpPost.addHeader("Content-Type",
"multipart/related; boundary=HereItGoes");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
FileBody bin = new FileBody(new File("./test.txt"));
builder.addPart("bin", bin);
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = client.execute(httpPost);
String responseString = new BasicResponseHandler()
.handleResponse(response);
System.out.println(responseString);
on the server, I print the number of parts, using this:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if (ServletFileUpload.isMultipartContent(request)) {
Iterator<Part> partsIterator = request.getParts().iterator();
System.out.println("The number of parts is :" + request.getParts().size());
and the answer is always zero, what mistake did i do ?
as @Jon Skeet, I was creating the request before adding the file. Now I reordered the code in which I put the execute
as the last line, and I still get the same thing, on the server the number of parts, is still zero
Look at when you're calling execute
- that's before you build the request properly! Just reorder your code so that you fully build the request, then you post it to get a response, then you use the response. (I'd also be personally surprised if using a URL in a File
constructor worked, but maybe there's something funky going on there... normally File
refers to a local filesystem file...)
See more on this question at Stackoverflow