Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

java - What did I miss to send a http part post request

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...