Sending data to the body of the HTTP request fails

I am using the J2ME HttpConnection class in my BlackBerry application to post data to a web server. I need to send the content of an image to the body of an HTTP request.

This is what I do

  • Get the bytes of a file in an array

  • Open HTTP connection

  • Set the title of the content type as image / jpeg

  • Get output stream of connection

  • Writing bytes to the output stream

  • Close output stream and connection

But the image is not uploaded to the server. What could be the problem?

Thanks.

EDIT - adding code

HttpConnection conn = null;
OutputStream out = null;

try{
    conn = new HttpConnection(Connector.open(myURL));
    conn.setRequestProperty("Content-Type", "image/jpeg");
    conn.setRequestMethod(HttpConnection.POST);
    conn.setRequestProperty("Content-Disposition", "form-data");
    conn.setRequestProperty("Connection", "Keep-Alive");

    out = conn.openOutputStream;
    out.write(buffer, 0, buffer.length);
    conn.setRequestProperty("Content-Length", buffer.length);
    out.flush();
}
catch(Exception e){
    e.printStackTrace();
}
finally{
    if(out != null)
        out.close();

    if(conn != null){
        System.out.println("" + conn.getResponseCode());
        conn.close();
    }
}

      

EDIT

The same code, when I try to use it with a string, works fine and sends the string to the server. But this is still a problem with the image bytes.

+1


a source to share


4 answers


A few things that may be missing from your list:



  • use HttpConnection.setRequestMethod (HttpConnection.POST) between 2 and 3.
  • set the content length with HttpConnection.setRequestProperty ("Content-Length", ...) between 5 and 6.
  • knowing that the HTTP request response code can help debug your problems: call HttpConnection.getResponseCode () after you've closed the OutputStream but before closing the HttpConnection.
+4


a source


conn = new HttpConnection (Connector.open (myURL));

This line is incorrect. Connection is a factory class that creates new Connection objects by looking at the appropriate protocol implementation.



HttpConnection conn = (HttpConnection) Connector.open(myURL);

      

The rest of the code looks fine. When you POSTING, in minimun you need to define the content type and content length.

+2


a source


You most definitely need to set all headers before sending the POST data, including the header Content-Length

.

Also, make sure you are sending request-only headers and not response-only headers.

+1


a source


You need to encode the bytes (preferably Base-64) and send that string. Raw bytes are unlikely to be http safe.

Then on the server you will need to decode them back to a byte array and do whatever you intend to do with it (save as file, stuff to database, etc.)

0


a source







All Articles