简体   繁体   中英

The server failed to respond with a valid HTTP response

I am trying to upload an xml file. While adding the file in binary format to HttpEntity with MultipartEntityBuilder, I am getting the following error

org.apache.http.ProtocolException: The server failed to respond with a valid HTTP response
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:149) ~[httpclient-4.5.3.jar:4.5.3]
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:56) ~[httpclient-4.5.3.jar:4.5.3]
    at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259) ~[httpcore-4.4.6.jar:4.4.6]

I have already gone through the link

https://www.baeldung.com/httpclient-multipart-upload

My understanding is that the file is not being accepted because the http entity cannot send MultipartEntityBuilder, but I can be wrong.


   HttpPost postRequest = new HttpPost("link to server");
   postRequest.setHeader("name1", "value");
   postRequest.setHeader("name2", "value2");
   File file1 = new File(file.getOriginalFilename());
   file1.createNewFile();
   FileOutputStream fileOutputStream = new FileOutputStream(file1);
   fileOutputStream.write(file.getBytes());
   fileOutputStream.close();
   MultipartEntityBuilder multipartEntityBuilder = 
   MultipartEntityBuilder.create();
   multipartEntityBuilder.addBinaryBody("file", file1);
   HttpEntity httpEntity = multipartEntityBuilder.create().addPart("file", new FileBody(file1)).build();
   postRequest.setEntity(httpEntity);

I suspect that your code is basically correct, but that either the server URL is wrong or the server just not answers correctly - in terms of the HTTP protocol.

If your code wouldn't be capable of sending correct HTTP requests, I'd expect the server to answer with a corresponding HTTP 4xx response code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM