Search in sources :

Example 1 with ProxyConfig

use of org.pdown.core.proxy.ProxyConfig in project proxyee-down by monkeyWie.

the class AppUtil method download.

/**
 * 下载http资源
 */
public static void download(String url, String path) throws IOException {
    URL u = new URL(url);
    HttpURLConnection connection;
    ProxyConfig proxyConfig = PDownConfigContent.getInstance().get().getProxyConfig();
    if (proxyConfig != null) {
        Type type;
        if (proxyConfig.getProxyType() == ProxyType.HTTP) {
            type = Type.HTTP;
        } else {
            type = Type.SOCKS;
        }
        if (!StringUtils.isEmpty(proxyConfig.getUser())) {
            Authenticator authenticator = new Authenticator() {

                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(proxyConfig.getUser(), proxyConfig.getPwd() == null ? null : proxyConfig.getPwd().toCharArray());
                }
            };
            Authenticator.setDefault(authenticator);
        }
        Proxy proxy = new Proxy(type, new InetSocketAddress(proxyConfig.getHost(), proxyConfig.getPort()));
        connection = (HttpURLConnection) u.openConnection(proxy);
    } else {
        connection = (HttpURLConnection) u.openConnection();
    }
    connection.setConnectTimeout(30000);
    connection.setReadTimeout(0);
    File file = new File(path);
    if (!file.exists() || file.isDirectory()) {
        FileUtil.createFileSmart(file.getPath());
    }
    try (InputStream input = connection.getInputStream();
        FileOutputStream output = new FileOutputStream(file)) {
        byte[] bts = new byte[8192];
        int len;
        while ((len = input.read(bts)) != -1) {
            output.write(bts, 0, len);
        }
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) InputStream(java.io.InputStream) ProxyConfig(org.pdown.core.proxy.ProxyConfig) URL(java.net.URL) ProxyType(org.pdown.core.proxy.ProxyType) Type(java.net.Proxy.Type) Proxy(java.net.Proxy) HttpURLConnection(java.net.HttpURLConnection) FileOutputStream(java.io.FileOutputStream) File(java.io.File) Authenticator(java.net.Authenticator) PasswordAuthentication(java.net.PasswordAuthentication)

Aggregations

File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1 InputStream (java.io.InputStream)1 Authenticator (java.net.Authenticator)1 HttpURLConnection (java.net.HttpURLConnection)1 InetSocketAddress (java.net.InetSocketAddress)1 PasswordAuthentication (java.net.PasswordAuthentication)1 Proxy (java.net.Proxy)1 Type (java.net.Proxy.Type)1 URL (java.net.URL)1 ProxyConfig (org.pdown.core.proxy.ProxyConfig)1 ProxyType (org.pdown.core.proxy.ProxyType)1