How to send POST data to a web server
This code snippet shows how you can send and receive information from/to a webserver using HTTP protocol's POST method using Java ME. It applies to Java ME with either MIDP 1.0 or MIDP 2.0.
Article Metadata
First load the required libraries:
import javax.microedition.io.*;
import java.io.*;
Then use this code in a function:
HttpConnection c = (HttpConnection) Connector.open("http://www.domain.com/url");
c.setRequestMethod(HttpConnection.POST);
byte[] data;
// data should be filled with binary data to send
c.setRequestProperty("Content-Length", Integer.toString(data.length));
OutputStream sending = c.openOutputStream();
sending.write(data);
sending.close();
If you want to send POST parameters to be read by PHP, ASP.NET or other server platform, you should make a string parameter like this
// This is a sample
String strData = "name=" + game.getName() + "&score=" + game.getScore();
byte[] data = strData.getBytes();
And also, you have to define an HTTP parameter like this:
c.setRequestProperty("Content-type", "application/x-www-form-urlencoded");


03 Sep
2009
This is a nice and to the point (short) article, very useful for first timers who try to send data to server using HTTP POST method.
It clearly defines, how to set HTTP Connection as POST, how to set the Content-length, how to convert Query String to byte[] data and send it over Output Stream.
I have seen lot new developers straggling with HTTP Post trying how to send Query string to server which they were sending while working with GET, it will help them all.
19 Sep
2009
This article is used to write or read a data from web server through post request. It has HttpConnection class that has a URL as an argument. This URL is not just a link but it is a file that will have been written or read through OutputStream Object.