Using HttpURLConnection

Usually when I want to make a request over network in java I familiar to use Socket class like this.

Socket theSock = new Socket(server,port);
PrintStream ps = new PrintStream(theSock.getOutputStream());

then uses ps.println() to send a request and uses theSock.getInputStream() to reciece response to see everything that sent over output stream. But this maybe not suitable for all situation.

Talking with web server will be done through HTTP message[request,response] that consists of header and body. So to make a post,get http request [with Socket class]
ps.println("POST uri HTTP/1.1");
ps.println("Content-Length: "+body.length());
ps.println("Content-Type: "+contenttype);

//or Get
ps.println("GET uri HTTP/1.1");
ps.println("Connection: Close");

and web server will responds with HTTP response like. Here's the example.
HTTP/1.1 200 OK
Date: Wed, 04 Jul 2007 10:14:54 GMT
Content-Length: 7
Connection: close
Content-Type: text/html


With this format it's hard to manage if we get the reponse via getInputStream() of Socket instance. How about Cookie or Session? or actual data in body. If the response is in xml format and we try to parse it like this
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(theSock.getInputStream());

It will throw "SAXException: Parsing Error : The root element is required in a well-formed document".
Instead of using using Socket class that saw only bits transfer over the network. HttpURLConnection class will alows us to read parameters in header and data in body. see the code.
//to make HTTP Post request with HttpURLConnection
URL url = new URL("http://server/uri");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();

then set some properties and make a request
conn.setAllowUserInteraction(false); // no user interact [like pop up]
conn.setDoOutput(true); // want to send
conn.setRequestProperty( "Content-type", "text/xml" );
conn.setRequestProperty( "Content-length", Integer.toString(contentx.length()));
OutputStream ost = conn.getOutputStream();
PrintWriter pw = new PrintWriter(ost);
pw.print(body); // here we "send" our body!

for Get Exam just change setRequestMethod to conn.setRequestMethod("GET").

To get body,cookie or other header parameter of HTTP response
int i=1;// this will print all header parameter
String hKey;
while ((hKey=conn.getHeaderFieldKey(i))!=null){
String hVal = conn.getHeaderField(i);
//and InputStream from here will be body

note: some time http get need to pass some parameter value, url to create in new URL("url") will end with something like field1=value1&field2=value2... This url must be encode with static method URLEncoder.encode(String) first.


Anonymous said...

It's useful


Saiful said...

was looking for this kind of post about why i should use HttpURLConnection...help me a lot thanks :)