HTTP GET request in java

时光总嘲笑我的痴心妄想 提交于 2019-12-11 23:15:15

问题


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?


回答1:


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();
    }
}



回答2:


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



来源:https://stackoverflow.com/questions/36140269/http-get-request-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!