Java HttpURLConnection使用proxy访问url

不使用proxy时代码:

    public static void main(String argv[]){
        String urlStr = "https://www.csdn.net/";
        try {
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
            String line = null;
            while ((line = br.readLine()) != null){
                System.out.println(line);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

使用proxy时,调用url.openConnection()函数时增加一个Proxy结构体作为参数。

    public static void main(String argv[]){
        String urlStr = "https://www.csdn.net/";
        try {
            URL url = new URL(urlStr);
            Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress("127.0.0.1"/*proxy addr*/,8080/*proxy port*/));
            HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
            String line = null;
            while ((line = br.readLine()) != null){
                System.out.println(line);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

除此之外,还可以使用设置环境变量的方法配置proxy。

System.setProperty("http.ProxySet","true");
System.setProperty("http.ProxyHost","127.0.0.1"/*proxyAddr*/);
System.setProperty("http.ProxyPort",8080/*proxy port*/);
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值