1

I'm trying to use http get request on java, to my localhost on port number 4567. I got the get request: "wget -q -O- http://localhost:4567/XXXX" [XXXX is some parameter - not relevent]. I've found a java library java.net.URLConnection for these kind of things but it seems that the URLConnection object is supposed to receive the url/port/.. and all other kind of parameters (In other words, you have to construct the object yourself), however, I got the full http get request as I've written above. Is there a way to simply 'shoot' the request without dealing with constructing the field for URLConnection?

Jayn
  • 45
  • 1
  • 3
  • 10

2 Answers2

4

You can create the URL object using your URL, it will figure out ports and other things itself. Ref : https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html

public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        URL oracle = new URL("http://localhost:4567/XXXX");
        URLConnection yc = oracle.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                                    yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) 
            System.out.println(inputLine);
        in.close();
    }
}
11thdimension
  • 10,333
  • 4
  • 33
  • 71
  • So, basically, when I'm using get request on http://localhost:4567/XXXX, it's the same as surfing to http://localhost:4567/XXXX and getting what's on there? (As you see I'm really new to this) – Jayn Mar 21 '16 at 20:05
  • 1
    Yes, when you open the link in the browser, browser creates a Socket at some random port (i.e. localhost:54820) and connects this socket to your server socket running at localhost:4567. Using it's local socket it downloads the content from the server and if it's something that it recognizes, it does some processing before rendering it. (like HTML, or XML). It's same for the URLConnection or WGEt, they will create a local socket but won't do anything extra, as they are just http clients. – 11thdimension Mar 21 '16 at 20:09
1

Why don't you use Apache HTTPClient library. It is simple to use.

HttpClient client = new HttpClient();

refer the document http://hc.apache.org/httpclient-3.x/tutorial.html

Amit Mahajan
  • 895
  • 6
  • 34