1
votes

I am using HttpClient 4.3.3. My task is to upload files onto a server. Following is my code:

    InputStream inputStream = new FileInputStream(new File("/path/to/file"));
    byte[] data;
    data = IOUtils.toByteArray(inputStream);
    InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data),"file-name-on-ser");

    MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();   

    multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    multipartEntity.addPart("file",inputStreamBody);

    HttpPost httpPost = new HttpPost("file upload URL");

    httpPost.setEntity(multipartEntity.build());

    CloseableHttpResponse response  = httpclient.execute(httpPost); 

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

      String line = "";

      while ((line = rd.readLine()) != null) 
      {
        System.out.println(line);
      }

When I run this code it successfully connects to the server.But the the output of the response is

         <html>
         <head><title>411 Length Required</title></head>
         <body bgcolor="white">
         <center><h1>411 Length Required</h1></center>
         <hr><center>server-name</center>
         </body>
         </html>

When I use firebug for debug, I see the following Request header.

Response Headersview source

Cache-Control no-store, no-cache

Connection keep-alive

Date Thu, 22 May 2014 08:58:02 GMT

Keep-Alive timeout=30

Server *****

Set-Cookie **** Path=/

Transfer-Encoding chunked

Request Headersview source

Accept text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8

Accept-Encoding gzip, deflate

Accept-Language en-US,en;q=0.5

Connection keep-alive

Cookie ****

Host *****

Referer https://****/shareupload/

User-Agent Mozilla/5.0 (Windows NT 6.1; rv:29.0) Gecko/20100101 Firefox/29.0

Request Headers From Upload Stream

Content-Length 12642

Content-Type multipart/form-data; boundary=---------------------------105143784893

I have seen similar questions on stack overflow.

1)411 Content-Length Required

2)File upload using apache's httpclient library not working

but still i am not able to find solution to my problem. Do I need to set up the Content-Length and Content-Type parameter in request header?

Thank you in advance.

1
I found stackoverflow.com/questions/10161578/… .Which could help in solving the problem.kshitij

1 Answers

1
votes

try like:

    InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data),"file-name-on-ser"){
            @Override
            public long getContentLength(){return data.length();}
    };