问题
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