【问题标题】:Get html file Java获取html文件Java
【发布时间】:2010-10-16 19:56:35
【问题描述】:

重复:

How do you Programmatically Download a Webpage in Java?

How to fetch html in Java

我正在开发一个应用程序,其中包括:用户输入某个网站的 URL,然后应用程序必须分析该 URL。

如何使用 Java 访问 HTML 文件?我需要使用 HttpRequest 吗? 它是如何工作的?

谢谢。

【问题讨论】:

    标签: java


    【解决方案1】:

    URLConnection 适用于简单的情况。当涉及到重定向之类的事情时,最好使用 Apache 的HTTPClient

    【讨论】:

      【解决方案2】:

      您可以只使用 URLConnection。请参阅来自 Sun 的 Java Tutorial

      【讨论】:

        【解决方案3】:

        此代码从 URL 下载数据,将其视为二进制内容:

        public class Download {
        
          private static void download(URL input, File output)
              throws IOException {
            InputStream in = input.openStream();
            try {
              OutputStream out = new FileOutputStream(output);
              try {
                copy(in, out);
              } finally {
                out.close();
              }
            } finally {
              in.close();
            }
          }
        
          private static void copy(InputStream in, OutputStream out)
              throws IOException {
            byte[] buffer = new byte[1024];
            while (true) {
              int readCount = in.read(buffer);
              if (readCount == -1) {
                break;
              }
              out.write(buffer, 0, readCount);
            }
          }
        
          public static void main(String[] args) {
            try {
              URL url = new URL("http://stackoverflow.com");
              File file = new File("data");
              download(url, file);
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        
        }
        

        这种方法的缺点是它忽略了任何元数据,例如 Content-Type,您可以通过使用 HttpURLConnection(或更复杂的 API,例如 Apache 的 API)获得。

        为了解析 HTML 数据,您需要一个专门的 HTML 解析器来处理格式不正确的标记,或者在使用 XML 解析器解析之前先tidy 它。

        【讨论】:

          【解决方案4】:

          您可以使用 java.net.URL 然后打开输入流以从服务器读取 HTML。请参阅示例here

          【讨论】:

            【解决方案5】:

            有趣的是,我在前一周编写了实用方法

            /**
             * Retrieves the file specified by <code>fileUrl</code> and writes it to 
             * <code>out</code>.
             * <p>
             * Does not close <code>out</code>, but does flush.
             * @param fileUrl The URL of the file.
             * @param out An output stream to capture the contents of the file
             * @param batchWriteSize The number of bytes to write to <code>out</code>
             *                       at once (larger files than this will be written
             *                       in several batches)
             * @throws IOException If call to web server fails
             * @throws FileNotFoundException If the call to the web server does not
             *                               return status code 200. 
             */
            public static void getFileStream(String fileURL, OutputStream out, int batchWriteSize)
                                        throws IOException{
                GetMethod get = new GetMethod(fileURL);
                HttpClient client = new HttpClient();
                HttpClientParams params = client.getParams();
                params.setSoTimeout(2000);
                client.setParams(params);
                try {
                    client.executeMethod(get);
                } catch(ConnectException e){
                    // Add some context to the exception and rethrow
                    throw new IOException("ConnectionException trying to GET " + 
                            fileURL,e);
                }
            
                if(get.getStatusCode()!=200){
                    throw new FileNotFoundException(
                            "Server returned " + get.getStatusCode());
                }
            
                // Get the input stream
                BufferedInputStream bis = 
                    new BufferedInputStream(get.getResponseBodyAsStream());
            
                // Read the file and stream it out
                byte[] b = new byte[batchWriteSize];
                int bytesRead = bis.read(b,0,batchWriteSize);
                long bytesTotal = 0;
                while(bytesRead!=-1) {
                    bytesTotal += bytesRead;
                    out.write(b, 0, bytesRead);
                    bytesRead = bis.read(b,0,batchWriteSize);;
                } 
                bis.close(); // Release the input stream.
                out.flush();        
            }
            

            使用 Apache Commons 库,即

            import org.apache.commons.httpclient.HttpClient;
            import org.apache.commons.httpclient.methods.GetMethod;
            import org.apache.commons.httpclient.params.HttpClientParams;
            

            【讨论】:

              猜你喜欢
              • 2014-03-29
              • 2011-06-03
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-06-22
              • 1970-01-01
              • 2018-06-22
              • 2021-11-22
              相关资源
              最近更新 更多