通过代理IP的HTTP URLConnection

将代理设置添加到 URLConnection 的示例,包括有无身份验证的两种情况,代码如下:

import java.io.BufferedReader;
import java.io.IOException;
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;
import java.net.URLConnection;

public class URLConnectionProxy {

    /**
     * The User Agent
     */
    private static final String AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.0.0 Safari/537.36";

    /**
     * Used to store the proxy settings
     */
    private Proxy proxy;

    /**
     * 
     * Method used to add proxy settings
     *
     * @param ip
     *            the proxy IP
     * @param port
     *            the proxy port
     */
    public void setProxy(String ip, int port) {
	this.proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip, port));
    }

    /**
     * 
     * Method used to add proxy settings with authentication
     *
     * @param ip
     * @param port
     * @param username
     * @param password
     */
    public void setProxy(String ip, int port, String username, String password) {
	this.proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip, port));
	Authenticator authenticator = new Authenticator() {

	    public PasswordAuthentication getPasswordAuthentication() {
		return (new PasswordAuthentication(username, password.toCharArray()));
	    }
	};
	Authenticator.setDefault(authenticator);

    }

    /**
     * The method will return the content in a {@link InputStream} object
     * 
     * @param domain
     *            The Domain name
     * 
     * @return the content as {@link InputStream} object
     * @throws Exception
     */
    private InputStream getContent(String domain) throws Exception {

	URL url = new URL(domain);
	URLConnection connection = null;
	if (this.proxy != null)
	    connection = url.openConnection(this.proxy);
	else
	    connection = url.openConnection();

	connection.setRequestProperty("User-Agent", AGENT);
	return connection.getInputStream();
    }

    /**
     * Method used to get URL content in {@link String} format
     * 
     * @param domain
     *            the {@link String} the URL
     * @return the {@link String} object returned
     * @throws Exception
     */
    public String getString(String domain) throws Exception {
	InputStream is = getContent(domain);
	StringBuilder sb = new StringBuilder();

	BufferedReader br = new BufferedReader(new InputStreamReader(is));
	String line;
	try {
	    while ((line = br.readLine()) != null) {
		sb.append(line);
	    }
	} catch (IOException e) {
	    e.printStackTrace();
	} finally {
	    /** finally block to close the {@link BufferedReader} */
	    if (br != null) {
		try {
		    br.close();
		} catch (IOException e) {
		    e.printStackTrace();
		}
	    }
	}
	return sb.toString();
    }

    public static void main(String[] args) throws Exception {
	System.out.println("URLConnection with Proxy Example");

	String url = "http://httpbin.org/get";
	URLConnectionProxy con = new URLConnectionProxy();

	/**
	 * activate this line if you are behind a proxy server - change the settings
	 * accordingly
	 */
	con.setProxy("127.0.0.1", 7000);

	/**
	 * activate this line if you are behind a proxy server with authentication -
	 * change the settings accordingly
	 */
	// con.setProxy("127.0.0.1", 7000, "user", "passowrd");

	String result = con.getString(url);

	System.out.println("URL: " + url);
	System.out.println();
	System.out.println(result);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值