如何在Java中进行HTTP GET?

137 java get http httpurlconnection

如何在Java中进行HTTP GET?

Kal*_*pak 200

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

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]));
   }
}
Run Code Online (Sandbox Code Playgroud)

  • +1代表完整代码 (26认同)
  • cletus答案(使用Apache HttpClient)的一个优点是HttpClient可以自动处理重定向和代理身份验证.您在此处使用的标准Java API类不会为您执行此操作.另一方面,使用标准API类的优点是您不需要在项目中包含第三方库. (9认同)
  • 很好的例子,但最好是捕获IOException而不是"general"Exception. (7认同)
  • 有必要设置超时或当前线程可能被阻止.参见`setConnectTimeout`和`setReadTimeout`. (4认同)

cle*_*tus 56

从技术上讲,你可以使用直接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();
Run Code Online (Sandbox Code Playgroud)

这是一个更完整的例子.

  • 这个项目已经结束了. (3认同)

HyL*_*ian 35

如果您不想使用外部库,则可以使用标准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
Run Code Online (Sandbox Code Playgroud)


Lau*_*ves 7

最简单的方法是不需要第三方库来创建URL对象,然后在其上调用openConnectionopenStream.请注意,这是一个非常基本的API,因此您无法对标头进行大量控制.