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*/);

你可能感兴趣的:(入门)