【问题标题】:How can I get HTML content from a specific URL on server side by using Java?如何使用 Java 从服务器端的特定 URL 获取 HTML 内容?
【发布时间】:2014-01-10 00:51:35
【问题描述】:

我正在设计一个应用程序,该应用程序需要使用 Java 从服务器端的特定 URL 加载 HTML 内容。我该如何解决?

问候,

【问题讨论】:

    标签: java web-scraping


    【解决方案1】:

    我已使用 Apache Commons HttpClient 库来执行此操作。看看这里: http://hc.apache.org/httpclient-3.x/tutorial.html

    它比 JDK HTTP 客户端支持功能更丰富。

    【讨论】:

    • 更新。来自 Apache Commons HttpClient 主页的引述:“Commons HttpClient 项目现已结束生命周期,不再进行开发。它已被 Apache HttpComponents 项目在其 HttpClientHttpCore 模块,提供更好的性能和更大的灵活性。”
    【解决方案2】:

    如果您只需要读取 url 而无需求助于第三方库,java 已内置支持检索 url。

    
    import java.net.*;
    import java.io.*;
    
    public class URLConnectionReader {
        public static void main(String[] args) throws Exception {
            URL yahoo = new URL("http://www.yahoo.com/");
            URLConnection yc = yahoo.openConnection();
            BufferedReader in = new BufferedReader(
                                    new InputStreamReader(
                                    yc.getInputStream()));
            String inputLine;
    
            while ((inputLine = in.readLine()) != null) 
                System.out.println(inputLine);
            in.close();
        }
    }
    

    【讨论】:

      【解决方案3】:

      如果是php,你可以使用cURL,但是因为它是java,你会使用HttpURLConnection,因为我刚刚在这个问题上发现:

      cURL equivalent in JAVA

      【讨论】:

        【解决方案4】:

        导入 java.io.BufferedReader; 导入 java.io.IOException; 导入 java.io.InputStreamReader; 导入 java.net.MalformedURLException; 导入 java.net.URL; 导入 java.net.URLConnection;

        公共类 URLConetent{ 公共静态 void main(String[] args) {

            URL url;
        
            try {
                // get URL content
        
                String a="http://localhost:8080//TestWeb/index.jsp";
                url = new URL(a);
                URLConnection conn = url.openConnection();
        
                // open the stream and put it into BufferedReader
                BufferedReader br = new BufferedReader(
                                   new InputStreamReader(conn.getInputStream()));
        
                String inputLine;
                while ((inputLine = br.readLine()) != null) {
                        System.out.println(inputLine);
                }
                br.close();
        
                System.out.println("Done");
        
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        
        }
        

        }

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-05-27
          • 2018-08-23
          • 1970-01-01
          • 2014-12-19
          • 2015-03-26
          相关资源
          最近更新 更多