如何在Java中执行HTTP GET请求?
如何在Java中执行HTTP GET请求?
如果你想要流式传输任何网页,你可以使用以下方法。
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
。 - Andersonint 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);
- H2ONaCl从技术上讲,你可以使用普通的TCP socket实现这个功能。然而我不建议这样做。我强烈建议你使用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();
这里有一个更加完整的示例。
如果你不想使用外部库,你可以使用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