Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 ?

Update 1

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
125 views
Welcome To Ask or Share your Answers For Others

1 Answer

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...)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...