Thursday, October 23, 2008

Java: Simple HTTPUrlConnection example

I’ve been a little lax in posting lately. Since I have been doing a little more network based programming in Java as of late, and I wanted to post some more basic programming articles, I felt I would kill two birds with one stone. Fortunately most of it has been simple HTTP based requests, so it has been pretty simple stuff in terms of implementation. Most of how to do so is well documented already, so I won’t echo what has been written better by others. Instead, I will just share a simple example of how to establish an HTTP GET request using the HttpURLConnection and display the results to the console.
package com.digiassn.blogspot;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class SimpleHTTPRequest {

/**
* @param args
*/
public static void main(String[] args) {
HttpURLConnection connection = null;
OutputStreamWriter wr = null;
BufferedReader rd = null;
StringBuilder sb = null;
String line = null;

URL serverAddress = null;

try {
serverAddress = new URL("http://localhost");
//set up out communications stuff
connection = null;

//Set up the initial connection
connection = (HttpURLConnection)serverAddress.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setReadTimeout(10000);

connection.connect();

//get the output stream writer and write the output to the server
//not needed in this example
//wr = new OutputStreamWriter(connection.getOutputStream());
//wr.write("");
//wr.flush();

//read the result from the server
rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
sb = new StringBuilder();

while ((line = rd.readLine()) != null)
{
sb.append(line + '\n');
}

System.out.println(sb.toString());

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally
{
//close the connection, set all objects to null
connection.disconnect();
rd = null;
sb = null;
wr = null;
connection = null;
}
}
}


Next post will show how to use the Apache HTTPClient to establish a Multi-Part form POST request.

20 comments:

Anonymous said...

it is useful

Anonymous said...

nice code
I used it in my website http://www.freelanceoverviews.com

Anonymous said...

thanks

Maksim said...

Thank you.

Anonymous said...

thank you very much!

Anonymous said...

useful thanks!

Anonymous said...

thanks for sharing this site. you can download various kinds of ebook from here

http://feboook.blogspot.com

Anonymous said...

Small Bug in Example:
If you plan to close the network connection after the HTTP call has been done with connection.disconnect(); you should also set connection.setRequestProperty("Connection", "close"); to avoid that the web server is waiting for further requests on the same network connection (disable keep-alive).

CAPS said...

Bingo.. It helped me to make a servlet's communication with local app.
Thanks a lot :)

Fredrik said...

Nice nice!

iklan-laris said...

thanks a lot buddy, it absolutely works :)

Anonymous said...

There is one inconsistency in this example: connection.setRequestMethod("GET");
connection.setDoOutput(true);

Now open the documentation http://developer.android.com/reference/java/net/HttpURLConnection.html
and read:

HttpURLConnection uses the GET method by default. It will use POST if setDoOutput(true) has been called. Other HTTP methods (OPTIONS, HEAD, PUT, DELETE and TRACE) can be used with setRequestMethod(String).

Anonymous said...

Useful example. May be connection.disconnect() is only if connection is not null ?

Anonymous said...

Works great! Thanks!

Eric G said...

This was exactly what I was looking for. The apache library is so heavy for such a simple task, this is bang on!

Great post!

Anonymous said...

Thank you very much! I've been struggling around this library for some time, this is the first example I've gotten to work, so I really appreciate it!

Anonymous said...

Thank you so much.

Eswar said...

I am trying to stop the existing application in tomcat

serverAddress = new URL("http://localhost:8080/manager/html/stop?path=/sampleProject");

But i got error only.
Error is:
java.io.IOException: Server returned HTTP response code: 401 for URL: http://localhost:8080/manager/html/stop?path=/sampleProject
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1615)

Help me.
Thanks in advance.

Anonymous said...

thank you very much!

Mobile Web Expert said...

Thanks for this, but the...
sb.append(line + '\n');
...line isn't so cracky either. This is better...
sb.append(line).append("\n");