0

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();
4
  • Can your server handle Content-Type = image/jpeg? Try to use some console or REST Client to test your request to find out if your request is correct. I think it should be Content-Type multipart/form-data Commented Jan 18, 2016 at 9:10
  • See this post stackoverflow.com/questions/8659808/… Commented Jan 18, 2016 at 9:12
  • @CyberAleks my server can handle that since am able to send the same file with the same content type using httpclient Commented Jan 18, 2016 at 9:13
  • @CyberAleks what reasons could make my httpurlconnection to fail while httpclient is working? Commented Jan 18, 2016 at 9:21

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

5 Comments

i have ended up implementing httpclient though i never wanted. my concern is how can i listen to upload progress? how can i update my progress bar using this http client?
Do you want a definite or indefinite progress bar? If you use onPreExecute and onPostExecute methods in an AsyncTask you can easily start and stop an indefinite progress bar
i want a definate one and am using ByteArrayEntity instance as my entity in my HttpPut put = new HttpPut(link); put.setEntity(bytearrayEntity)
I think this may be what you are after stackoverflow.com/questions/9854555/…
men your second link in your last comment worked. please add it to your answer and i will accept it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.