java 抓取網頁內容,可設定代理(HttpURLConnection)

來源:互聯網
上載者:User

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;

/**
 **網頁抓取 通用類
 * @author
 */
public class WebClient {

    /**
     *Proxy 伺服器的地址
     */
    private static String proxyHost;
    /**
     * Proxy 伺服器的連接埠
     */
    private static String proxyPort;
    /**
     * Proxy 伺服器使用者名稱
     */
    private static String proxyUser;
    /**
     * Proxy 伺服器密碼
     */
    private static String proxyPassword;

    /**
     *網頁抓取方法
     * @param urlString      要抓取的url地址
     * @param charset        網頁編碼方式
     * @param timeout        逾時時間
     * @return               抓取的網頁內容
     * @throws IOException   抓取異常
     */
    public static String GetWebContent(String urlString, final String charset, int timeout) throws IOException {
        if (urlString == null || urlString.length() == 0) {
            return null;
        }
        urlString = (urlString.startsWith("http://") ||
urlString.startsWith("https://")) ? urlString : ("http://" +
urlString).intern();
        URL url = new URL(urlString);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        GetProxy();
        conn.setRequestProperty(
                "User-Agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");//增加前序,類比瀏覽器,防止屏蔽
        conn.setRequestProperty("Accept", "text/html");//只接受text/html類型,當然也可以接受圖片,pdf,*/*任意,就是tomcat/conf/web裡面定義那些

        conn.setConnectTimeout(timeout);
        try {
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        InputStream input = conn.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(input,
                charset));
        String line = null;
        StringBuffer sb = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\r\n");
        }
        if (reader != null) {
            reader.close();
        }
        if (conn != null) {
            conn.disconnect();
        }
        return sb.toString();

    }

    /**
     * 網頁抓取方法
     * @param urlString      要抓取的url地址
     * @return               抓取的網頁內容
     * @throws IOException   抓取異常
     */
    public static String GetWebContent(String urlString) throws IOException {
        return GetWebContent(urlString, "iso-8859-1", 5000);
    }

    /**
     * 網頁抓取方法
     * @param urlString      要抓取的url地址
     * @param pageCharset  目標網頁編碼方式
     * @return               抓取的網頁內容
     * @throws IOException   抓取異常
     */
    public static String GetWebContent(String urlString, String pageCharset) throws IOException {
        String strHTML = GetWebContent(urlString, "iso-8859-1", 5000);
        String StrEncode = new String(strHTML.getBytes("iso-8859-1"), pageCharset);
        return StrEncode;
    }

    /**
     * 設定Proxy 伺服器
     * @param proxyHost
     * @param proxyPort
     */
    public static void SetProxy(String proxyHost, String proxyPort) {
        SetProxy(proxyHost, proxyPort, null, null);
    }

    /**
     * 設定Proxy 伺服器
     * @param proxyHost       Proxy 伺服器的地址
     * @param proxyPort       Proxy 伺服器的連接埠
     * @param proxyUser       Proxy 伺服器使用者名稱
     * @param proxyPassword   Proxy 伺服器密碼
     */
    public static void SetProxy(String sproxyHost, String sproxyPort, String sproxyUser, String sproxyPassword) {
        proxyHost = sproxyHost;
        proxyPort = sproxyPort;
        if (sproxyPassword != null && sproxyPassword.length() > 0) {
            proxyUser = sproxyUser;
            proxyPassword = sproxyPassword;
        }
    }

    /**
     * 取得代理設定
     * @return
     */
    private static Properties GetProxy() {
        Properties propRet = null;
        if (proxyHost != null && proxyHost.length() > 0) {
            propRet = System.getProperties();
            // 設定http訪問要使用的Proxy 伺服器的地址
            propRet.setProperty("http.proxyHost", proxyHost);
            // 設定http訪問要使用的Proxy 伺服器的連接埠
            propRet.setProperty("http.proxyPort", proxyPort);
            if (proxyUser != null && proxyUser.length() > 0) {
                //使用者名稱密碼
                propRet.setProperty("http.proxyUser", proxyUser);
                propRet.setProperty("http.proxyPassword", proxyPassword);
            }
        }

        return propRet;
    }

    /**
     * 類測試函數
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        //SetProxy("10.10.10.10", "8080");//Proxy 伺服器設定
        String s = GetWebContent("http://www.my400800.cn", "utf-8");      
        System.out.println(s);
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.