【发布时间】:2010-12-01 22:11:59
【问题描述】:
如何在 Java 中执行 HTTP GET?
【问题讨论】:
标签: java http get httpurlconnection
如何在 Java 中执行 HTTP GET?
【问题讨论】:
标签: java http get httpurlconnection
如果你想串流任何网页,你可以使用下面的方法。
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");
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()))) {
for (String line; (line = reader.readLine()) != null; ) {
result.append(line);
}
}
return result.toString();
}
public static void main(String[] args) throws Exception
{
System.out.println(getHTML(args[0]));
}
}
【讨论】:
setConnectTimeout 和setReadTimeout。
int readSize = 100000; int destinationSize = 1000000; char[] destination = new char[destinationSize]; int returnCode; int offset = 0; while ((returnCode = bufferedReader.read(destination, offset, readSize)) != -1) { offset += returnCode; if (offset >= destinationSize) throw new Exception(); } bufferedReader.close(); return (new String(destination)).substring(0, offset+returnCode+1);
如果您不想使用外部库,可以使用标准 Java API 中的 URL 和 URLConnection 类。
一个例子如下所示:
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
【讨论】:
从技术上讲,您可以使用直接的 TCP 套接字来做到这一点。不过我不会推荐它。我强烈建议您改用Apache HttpClient。在其simplest form:
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();
这里还有一个complete example。
【讨论】:
不需要第三方库的最简单方法是创建URL 对象,然后在其上调用openConnection 或openStream。请注意,这是一个非常基本的 API,因此您不会对标头进行太多控制。
【讨论】: