JAVA如何正确使用爬虫代理

HttpClient3.1
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;

import java.io.IOException;

public class Main {
private static final String PROXY_HOST = “t.16yun.cn”;
private static final int PROXY_PORT = 31111;

public static void main(String[] args) {
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod("https://httpbin.org/ip");

    HostConfiguration config = client.getHostConfiguration();
    config.setProxy(PROXY_HOST, PROXY_PORT);

    client.getParams().setAuthenticationPreemptive(true);

    String username = "16ABCCKJ";
    String password = "712323";
    Credentials credentials = new UsernamePasswordCredentials(username, password);
    AuthScope authScope = new AuthScope(PROXY_HOST, PROXY_PORT);

    client.getState().setProxyCredentials(authScope, credentials);

    try {
        client.executeMethod(method);

        if (method.getStatusCode() == HttpStatus.SC_OK) {
            String response = method.getResponseBodyAsString();
            System.out.println("Response = " + response);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        method.releaseConnection();
    }
}

}
点击此链接了解更多 www.16yun.cn

你可能感兴趣的:(数据采集,爬虫代理,http代理,网络爬虫)