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();
Edijae Crusar
  • 3,473
  • 3
  • 37
  • 74
  • 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 – CyberAleks Jan 18 '16 at 09:10
  • See this post http://stackoverflow.com/questions/8659808/how-does-http-file-upload-work – CyberAleks Jan 18 '16 at 09:12
  • @CyberAleks my server can handle that since am able to send the same file with the same content type using httpclient – Edijae Crusar Jan 18 '16 at 09:13
  • @CyberAleks what reasons could make my httpurlconnection to fail while httpclient is working? – Edijae Crusar Jan 18 '16 at 09:21

1 Answers1

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

Community
  • 1
  • 1
BenJ
  • 456
  • 2
  • 7
  • 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? – Edijae Crusar Jan 18 '16 at 10:51
  • 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 – BenJ Jan 18 '16 at 10:54
  • i want a definate one and am using `ByteArrayEntity` instance as my entity in my `HttpPut put = new HttpPut(link); ` `put.setEntity(bytearrayEntity)` – Edijae Crusar Jan 18 '16 at 11:01
  • I think this may be what you are after https://stackoverflow.com/questions/9854555/android-http-upload-progress-for-urlencodedformentity – BenJ Jan 18 '16 at 11:04
  • men your second link in your last comment worked. please add it to your answer and i will accept it – Edijae Crusar Jan 19 '16 at 08:22