龙空技术网

Java,客户端HttpURLConnection和HttpsURLConnection使用代理

古怪今人 101

前言:

眼前朋友们对“http代理java”大概比较讲究,朋友们都想要了解一些“http代理java”的相关内容。那么小编在网络上搜集了一些关于“http代理java””的相关文章,希望我们能喜欢,我们一起来学习一下吧!

说明:

上节,实现HTTP/HTTPS代理服务器,其中Http代理就是普通代理,https代理就是隧道代理,服务端已实现,本节的目标是,Java作为客户端是如何使用普通代理及隧道代理,案例如下。

HttpURLConnection使用代理:

场景,使用HTTP代理,发起http调用。

package com.what21.netty03.demo02;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.InetSocketAddress;import java.net.Proxy;import java.net.ProxySelector;import java.net.URI;import java.net.URL;import java.util.List;public class HttpProxyClientForHttp {    /**     * 通过系统属性设置代理     *     * @param proxyAddr     * @param proxyPort     */    private static void setProxy(String proxyAddr, int proxyPort) {        System.setProperty("java.net.useSystemProxies", "true");        // HTTP代理        System.setProperty("http.proxyHost", proxyAddr);        System.setProperty("http.proxyPort", proxyPort + "");        // HTTPS代理        System.setProperty("https.proxyHost", proxyAddr);        System.setProperty("https.proxyPort", proxyPort + "");    }    /**     * @param uri     * @return     */    private static Proxy getSystemProxy(String uri) {        Proxy proxy = null;        try {            ProxySelector ps = ProxySelector.getDefault();            List<Proxy> proxyList = ps.select(new URI(uri));            for (Proxy p : proxyList) {                // System.out.println("代理类型 : " + p.type());                InetSocketAddress addr = (InetSocketAddress) p.address();                if (addr == null) {                    System.out.println("没有代理");                } else {                    proxy = p;                    System.out.println("代理主机 : " + addr.getHostName());                    System.out.println("代理端口 : " + addr.getPort());                }            }        } catch (Exception e) {            e.printStackTrace();        }        return proxy;    }    /**     * @param use     */    private static void invoke(boolean use) {        // 通过系统属性设置代理        setProxy("127.0.0.1",8888);        String urlStr = ";;        // 获取代理        Proxy proxy = getSystemProxy(urlStr);        try {            URL url = new URL(urlStr);            HttpURLConnection conn = null;            if (use) {                // 使用代理代开资源                conn = (HttpURLConnection) url.openConnection(proxy);                System.out.println("使用了代理代开资源");            } else {                conn = (HttpURLConnection) url.openConnection();            }            conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");            // 超时时间            conn.setConnectTimeout(10000);            InputStream is = conn.getInputStream();            BufferedReader in = new BufferedReader(new InputStreamReader(is));            StringBuffer text = new StringBuffer();            String line = null;            while ((line = in.readLine()) != null) {                text.append(line);            }            if (is != null) {                is.close();            }            if (conn != null) {                conn.disconnect();            }            // 打印内容            System.out.println(text.toString());        } catch (Exception e) {            e.printStackTrace();        }    }    /**     * @param args     */    public static void main(String[] args) {        invoke(false);    }}
HttpsURLConnection使用代理:

场景,使用HTTPS代理,发起https调用。

package com.what21.netty03.demo02;import javax.net.ssl.HttpsURLConnection;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.net.Authenticator;import java.net.InetSocketAddress;import java.net.PasswordAuthentication;import java.net.Proxy;import java.net.URL;public class HttpProxyClientForHttps {    /**     * 设置代理     *     * @param proxyAddr     * @param proxyPort     */    private static Proxy createProxy(String proxyAddr, int proxyPort) {        // 设置认证        Authenticator.setDefault(new Authenticator() {            protected PasswordAuthentication getPasswordAuthentication() {                return new PasswordAuthentication("username", "password"                        .toCharArray());            }        });        // 设置HTTP代理        Proxy proxy = new Proxy(Proxy.Type.HTTP,                new InetSocketAddress(proxyAddr, proxyPort));        return proxy;    }    /**     * @param use     */    private static void invoke(boolean use) {        String urlStr = ";;        // 创建代理对象        Proxy proxy = createProxy("127.0.0.1", 8888);        try {            URL url = new URL(urlStr);            HttpsURLConnection conn = null;            if (use) {                // 使用代理代开资源                conn = (HttpsURLConnection) url.openConnection();                System.out.println("使用了代理代开资源");            } else {                conn = (HttpsURLConnection) url.openConnection();            }            conn.setRequestProperty("Charset", "UTF-8");            conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");            // 超时时间            conn.setConnectTimeout(10000);            InputStream is = conn.getInputStream();            BufferedReader in = new BufferedReader(new InputStreamReader(is));            StringBuffer text = new StringBuffer();            String line = null;            while ((line = in.readLine()) != null) {                text.append(line);            }            if (is != null) {                is.close();            }            if (conn != null) {                conn.disconnect();            }            // 打印内容            System.out.println(text.toString());        } catch (Exception e) {            e.printStackTrace();        }    }    /**     * @param args     */    public static void main(String[] args) {        invoke(true);    }}

标签: #http代理java