Search code examples
javaandroidhttpurlconnectionandroid-networking

HTTP_BAD_REQUEST errors while sending image files using HttpUrlConnection


I have a problem sending images to my server using httpurlconnection. i have read Android documentation and another HttpUrlconnection implementation but i don't know where am doing it the wrong way since am getting a HTTP_BAD_REQUEST error code(400). what important thing am i missing in my code below?

My response code always return 400 but my link is ok since am able to achieve this using httpclient

 link = "my link.com";

 try {
   URL   url = new URL(link);

   connection = (HttpURLConnection)url.openConnection();
   connection.setRequestMethod("POST");
   connection.setDoOutput(true);
   connection.setUseCaches(false);
   connection.setChunkedStreamingMode(0);
   connection.setRequestProperty("Content-Type", "image/jpeg");

   BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream());
   FileInputStream stream = new FileInputStream(file);
   byte[] buffer = new byte[1024];
   int bytesRead;
   while ((bytesRead =stream.read(buffer ,0 ,buffer.length)) != -1){
            outputStream.write(buffer);
            outputStream.flush();
   }
  outputStream.flush();

  responseCode = connection.getResponseCode();

Solution

  • I think the issue is how the image is being added to the output stream. All of the connection configuration steps look good.

    I tried this method recently and it worked well:

    https://vikaskanani.wordpress.com/2011/01/11/android-upload-image-or-file-using-http-post-multi-part/

    It is also good practice to wrap in an AsyncTask. I have noticed that MultipartEntity is now deprecated, but you can replace with MultipartEntityBuilder.

    update

    To listen to file upload events and update your progressbar, You can override the writeTo method of any HttpEntity implementation and count bytes as they get written to the output stream.

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
       HttpPost httppost = new HttpPost("http://www.google.com/sorry");
    
       MultipartEntity outentity = new MultipartEntity() {
    
        @Override
        public void writeTo(final OutputStream outstream) throws IOException {
            super.writeTo(new CoutingOutputStream(outstream));
        }
    
       };
       outentity.addPart("stuff", new StringBody("Stuff"));
       httppost.setEntity(outentity);
    
       HttpResponse rsp = httpclient.execute(httppost);
       HttpEntity inentity = rsp.getEntity();
       EntityUtils.consume(inentity);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
    
    static class CoutingOutputStream extends FilterOutputStream {
    
        CoutingOutputStream(final OutputStream out) {
            super(out);
        }
    
        @Override
        public void write(int b) throws IOException {
            out.write(b);
            System.out.println("Written 1 byte");
        }
    
        @Override
        public void write(byte[] b) throws IOException {
            out.write(b);
            System.out.println("Written " + b.length + " bytes");
        }
    
        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            out.write(b, off, len);
            System.out.println("Written " + len + " bytes");
        }
    
    }
    

    update If you would like to update a progress bar based on the http progress this link provides a great example

    Link