如何在 Java 中执行 HTTP GET?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1485708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I do a HTTP GET in Java?
提问by
How do I do a HTTP GET in Java?
如何在 Java 中执行 HTTP GET?
回答by cletus
Technically you could do it with a straight TCP socket. I wouldn't recommend it however. I would highly recommend you use Apache HttpClientinstead. In its simplest form:
从技术上讲,您可以使用直接的 TCP 套接字来实现。然而,我不会推荐它。我强烈建议您改用Apache HttpClient。以其最简单的形式:
GetMethod get = new GetMethod("http://httpcomponents.apache.org");
// execute method and handle any error responses.
...
InputStream in = get.getResponseBodyAsStream();
// Process the data from the input stream.
get.releaseConnection();
and here is a more complete example.
这是一个更完整的例子。
回答by Kalpak
If you want to stream any webpage, you can use the method below.
如果您想流式传输任何网页,可以使用以下方法。
import java.io.*;
import java.net.*;
public class c {
public static String getHTML(String urlToRead) throws Exception {
StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
public static void main(String[] args) throws Exception
{
System.out.println(getHTML(args[0]));
}
}
回答by Laurence Gonsalves
The simplest way that doesn't require third party libraries it to create a URLobject and then call either openConnectionor openStreamon it. Note that this is a pretty basic API, so you won't have a lot of control over the headers.
不需要第三方库的最简单方法是创建一个URL对象,然后在它上面调用openConnection或openStream。请注意,这是一个非常基本的 API,因此您不会对标头进行大量控制。
回答by HyLian
If you dont want to use external libraries, you can use URL and URLConnection classes from standard Java API.
如果不想使用外部库,可以使用标准 Java API 中的 URL 和 URLConnection 类。
An example looks like this:
一个示例如下所示:
String urlString = "http://wherever.com/someAction?param1=value1¶m2=value2....";
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
// Do what you want with that stream