如何在Java中进行HTTP GET请求?

154

如何在Java中执行HTTP GET请求?


2
https://dev59.com/vHE85IYBdhLWcg3wZyqt - Pacerier
1
您还可以使用 Java 11 的新 HTTP Client API。请参阅此帖子 - Mahozad
4个回答

238

如果你想要流式传输任何网页,你可以使用以下方法。

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]));
   }
}

9
使用Apache HttpClient的Cletus答案的优点之一是,HttpClient可以自动处理重定向和代理身份验证。您在此处使用的标准Java API类不会为您处理这些内容。另一方面,使用标准API类的优点是您无需在项目中包含第三方库。 - Jesper
1
另外,URL类无法获取用于解码结果的字符集。 - Nick Bolton
7
好的例子,但最好捕获 IOException 而不是“通用”异常。 - adalpari
5
必须设置超时时间,否则当前线程可能会被阻塞。请参见setConnectTimeoutsetReadTimeout - Anderson
1
以上解决方案使读取的长度等于行长度,即使HTML没有行的概念。它还会丢弃CR和LF字符。另一种选择是: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); - H2ONaCl
显示剩余4条评论

59

从技术上讲,你可以使用普通的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();

这里有一个更加完整的示例


3
这个项目已经结束。 - shredding

41

如果你不想使用外部库,你可以使用Java标准API中的URL和URLConnection类。

一个示例看起来像这样:

String urlString = "http://wherever.com/someAction?param1=value1&param2=value2....";
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
// Do what you want with that stream

1
@HyLian:鉴于 OP 问题的表面水平,您的代码片段应该包含 try { } finally { } 来进行清理。 - Stephen C
@Stephen C:当然,那只是一个代码片段,用来展示游戏中有哪些类以及如何使用它们。如果你把它放到一个真正的程序中,你应该遵守异常规则 :) - HyLian
InputStream = 所有服务器发送给我们的内容? - CodeGuru
您需要包括问题中的“GET”部分-这里缺少了GET-请参阅下面的答案。 - user1743310

9
最简单的方法是创建一个URL对象,然后调用openConnectionopenStream方法。请注意,这是一个相当基本的API,因此您无法对标头进行很多控制。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接