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.
a source to share
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.
a source to share
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.
a source to share