tags:

views:

99

answers:

6

I want setup a http connection to send request and get the response in an stand alone java application, can any one help me how can i proceed with this????

+1  A: 

You can use URLConnection class bundled with standard Java (since JDK 1.0!), or a higher level HTTP client such as Apache's HTTPCLIENT which will provide, in addition to plain HTTP, higher level components like cookies, standard headers and more.

Pablo Santa Cruz
+4  A: 
HttpURLConnection connection = null;
    try {
        URL url = new URL("www.google.com");
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        connection.getInputStream();
                    // do something with the input stream here

    } catch (MalformedURLException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    } finally {
        if(null != connection) { connection.disconnect(); }
    }
MikeG
For safety, you should check for null on your connection reference in the finally block
Jeroen Rosenberg
@Jeroen - Good point, agreed. I'll update.
MikeG
Getting exception ....java.net.ConnectException: Connection timed out: connect
@jeroen / mike if the response is html how can i get it??
@user323101 - you can wrap the InputStream returned from the connection in a BufferedReader, and use a StringBuilder to append each line returned from bufferedReader.readLine().
MikeG
A: 

This is how I handle AJAX. Basically just change the URL variable and the "onreadystatechange" function

function getSuggestions(type){
    if(type == "") {
        document.getElementById("entries").innerHTML="test"
        return;
    }

    var r = getXmlObject();
    var url= "getData.php?status="+type;

    if (r.readyState == 4 || r.readyState == 0) {

        r.open("POST", url, true);

        r.onreadystatechange = function (){
            if (r.readyState == 4) {
                document.getElementById("entries").innerHTML= r.responseText; 
            }
        };

        r.send(null);

    }   
}


function getXmlObject() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else if(window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        alert('Status: Cound not create XmlHttpRequest Object. Consider upgrading your browser.');
    }
}
Dutchie432
??? The question is about java, not javascript!!!
seanizer
Huh. Whaddya know.
Dutchie432
A: 

A couple of answers have already pointed out Apache HTTP Client, but they link to version 3.x, which is no longer maintained. You should use version 4, which has a slightly different API, if you want to use this library: http://hc.apache.org/httpcomponents-client-4.0.1/index.html

Bruno
+1  A: 

You can view a extensive tutorial/example on how to use Java HttpURLConnection to do requests and response from BalusC, How to use java.net.URLConnection to fire and handle HTTP requests?

The Elite Gentleman