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:

  1. Anonymous4:10 AM

    it is useful

    ReplyDelete
  2. Anonymous3:16 PM

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

    ReplyDelete
  3. Anonymous6:33 AM

    thanks

    ReplyDelete
  4. Anonymous6:45 AM

    thank you very much!

    ReplyDelete
  5. Anonymous3:37 AM

    useful thanks!

    ReplyDelete
  6. Anonymous8:02 PM

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

    http://feboook.blogspot.com

    ReplyDelete
  7. Anonymous5:21 PM

    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).

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

    ReplyDelete
  9. Fredrik11:43 AM

    Nice nice!

    ReplyDelete
  10. thanks a lot buddy, it absolutely works :)

    ReplyDelete
  11. Anonymous10:01 AM

    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).

    ReplyDelete
  12. Anonymous7:23 AM

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

    ReplyDelete
  13. Anonymous8:25 AM

    Works great! Thanks!

    ReplyDelete
  14. 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!

    ReplyDelete
  15. Anonymous11:52 AM

    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!

    ReplyDelete
  16. Anonymous9:00 AM

    Thank you so much.

    ReplyDelete
  17. 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.

    ReplyDelete
  18. Anonymous3:28 AM

    thank you very much!

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

    ReplyDelete