如何在 Java 中执行 HTTP GET?
2022-08-31 07:31:39
如何在 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]));
}
}
从技术上讲,您可以使用直接的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();
这是一个更完整的例子。