【问题标题】:Java http connectionJava http 连接
【发布时间】:2011-04-06 20:30:48
【问题描述】:

我想设置一个 http 连接来发送请求并在一个独立的 java 应用程序中获取响应,谁能帮我解决这个问题????

【问题讨论】:

  • 顺便说一句,如果它对您最有帮助,请随时“接受”一个答案。 (尽管您可能是未注册用户,我不确定这是否可能?)

标签: java http https


【解决方案1】:

您可以使用与标准 Java 捆绑在一起的 URLConnection 类(自 JDK 1.0 起!),或更高级别的 HTTP 客户端,例如 Apache's HTTPCLIENT,除了普通 HTTP 之外,它还提供更高级别的组件,如 cookie、标准标头等等。

【讨论】:

    【解决方案2】:
    HttpURLConnection connection = null;
        try {
            URL url = new URL("www.google.com");
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            connection.getInputStream();
                        // do something with the input stream here
    
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            if(null != connection) { connection.disconnect(); }
        }
    

    【讨论】:

    • 为了安全,您应该在 finally 块中检查您的连接引用是否为空
    • @jeroen / mike 如果响应是 html 我怎么能得到它??
    • @user323101 - 您可以将从连接返回的 InputStream 包装在 BufferedReader 中,并使用 StringBuilder 附加从 bufferedReader.readLine() 返回的每一行。
    【解决方案3】:

    一些答案​​已经指出了 Apache HTTP 客户端,但它们链接到不再维护的 3.x 版本。如果你想使用这个库,你应该使用版本 4,它的 API 略有不同:http://hc.apache.org/httpcomponents-client-4.0.1/index.html

    【讨论】:

      猜你喜欢
      • 2014-01-12
      • 1970-01-01
      • 2017-11-09
      • 1970-01-01
      • 2012-02-05
      • 2016-03-04
      • 2017-07-15
      • 1970-01-01
      • 2018-09-20
      相关资源
      最近更新 更多