HoRain云--如何在Java中使用HTTP代理

  

HoRain 云小助手个人主页

⛺️生活的理想,就是为了理想的生活!


⛳️ 推荐

前些天发现了一个超棒的服务器购买网站,性价比超高,大内存超划算!忍不住分享一下给大家。点击跳转到网站。

目录

⛳️ 推荐

一、全局代理设置(所有网络请求生效)

1.1 启动参数配置(推荐)

1.2 代码动态配置

二、原生 HttpURLConnection 代理配置

2.1 基础代理设置

2.2 认证自动处理

三、Apache HttpClient 5.x 代理配置

3.1 经典配置方案

3.2 路由级代理配置

四、OkHttp 3 代理配置

4.1 基础代理设置

4.2 动态代理选择

五、Spring RestTemplate 代理配置

5.1 基于 SimpleClientHttpRequestFactory

5.2 Apache HttpClient 集成方案

六、生产环境最佳实践

6.1 代理配置管理

6.2 代理异常处理

七、代理检测与调试

7.1 验证代理是否生效

7.2 网络流量监控



一、全局代理设置(所有网络请求生效)

1.1 启动参数配置(推荐)

# 命令行启动时设置
java -Dhttp.proxyHost=proxy.example.com \
     -Dhttp.proxyPort=3128 \
     -Dhttps.proxyHost=proxy.example.com \
     -Dhttps.proxyPort=3128 \
     -Dhttp.nonProxyHosts="localhost|127.0.0.1|*.internal" \
     YourApplication

1.2 代码动态配置

System.setProperty("http.proxyHost", "proxy.example.com");
System.setProperty("http.proxyPort", "3128");
System.setProperty("https.proxyHost", "proxy.example.com");
System.setProperty("https.proxyPort", "3128");

二、原生 HttpURLConnection 代理配置

2.1 基础代理设置

URL url = new URL("https://api.example.com");
Proxy proxy = new Proxy(Proxy.Type.HTTP, 
    new InetSocketAddress("proxy.example.com", 3128));

HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
conn.setRequestMethod("GET");

// 添加代理认证(如果需要)
String auth = "user:password";
String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());
conn.setRequestProperty("Proxy-Authorization", "Basic " + encodedAuth);

2.2 认证自动处理

Authenticator.setDefault(new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        if (getRequestorType() == RequestorType.PROXY) {
            return new PasswordAuthentication("user", "password".toCharArray());
        }
        return null;
    }
});

三、Apache HttpClient 5.x 代理配置

3.1 经典配置方案

HttpHost proxy = new HttpHost("proxy.example.com", 3128);

CloseableHttpClient client = HttpClients.custom()
    .setProxy(proxy)
    .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy())
    .setDefaultCredentialsProvider(new BasicCredentialsProvider() {{
        setCredentials(new AuthScope(proxy), 
            new UsernamePasswordCredentials("user", "password".toCharArray()));
    }})
    .build();

3.2 路由级代理配置

HttpClientContext context = HttpClientContext.create();
RequestConfig config = RequestConfig.custom()
    .setProxy(proxy)
    .build();

HttpGet request = new HttpGet("https://api.example.com");
request.setConfig(config);

client.execute(request, context, response -> {
    // 处理响应
    return null;
});

四、OkHttp 3 代理配置

4.1 基础代理设置

Proxy proxy = new Proxy(Proxy.Type.HTTP, 
    new InetSocketAddress("proxy.example.com", 3128));

OkHttpClient client = new OkHttpClient.Builder()
    .proxy(proxy)
    .proxyAuthenticator((route, response) -> {
        String credential = Credentials.basic("user", "password");
        return response.request().newBuilder()
            .header("Proxy-Authorization", credential)
            .build();
    })
    .build();

4.2 动态代理选择

client = new OkHttpClient.Builder()
    .proxySelector(new ProxySelector() {
        @Override
        public List select(URI uri) {
            // 根据URI动态选择代理
            return Arrays.asList(new Proxy(Proxy.Type.HTTP, 
                new InetSocketAddress("proxy.example.com", 3128)));
        }

        @Override
        public void connectFailed(URI uri, 
            SocketAddress sa, IOException ioe) {
            // 处理连接失败
        }
    })
    .build();

五、Spring RestTemplate 代理配置

5.1 基于 SimpleClientHttpRequestFactory

@Bean
public RestTemplate restTemplate() {
    Proxy proxy = new Proxy(Proxy.Type.HTTP, 
        new InetSocketAddress("proxy.example.com", 3128));

    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    factory.setProxy(proxy);
    
    return new RestTemplate(factory);
}

5.2 Apache HttpClient 集成方案

@Bean
public RestTemplate restTemplate() {
    HttpHost proxy = new HttpHost("proxy.example.com", 3128);
    
    CloseableHttpClient client = HttpClients.custom()
        .setProxy(proxy)
        .setDefaultCredentialsProvider(new BasicCredentialsProvider() {{
            setCredentials(new AuthScope(proxy), 
                new UsernamePasswordCredentials("user", "password"));
        }})
        .build();

    return new RestTemplate(new HttpComponentsClientHttpRequestFactory(client));
}

六、生产环境最佳实践

6.1 代理配置管理

# application.properties
proxy.enable=true
proxy.host=proxy.example.com
proxy.port=3128
proxy.user=${PROXY_USER}
proxy.password=${PROXY_PASSWORD}  # 从环境变量读取

6.2 代理异常处理

try {
    // 执行代理请求
} catch (ConnectException e) {
    if (e.getMessage().contains("Connection refused")) {
        throw new ProxyConnectException("代理服务器不可达", e);
    }
} catch (SocketTimeoutException e) {
    throw new ProxyTimeoutException("代理连接超时", e);
}

七、代理检测与调试

7.1 验证代理是否生效

System.out.println(System.getProperty("http.proxyHost")); // 查看全局代理
System.out.println(request.url().host()); // 查看实际请求目标

7.2 网络流量监控

# 使用tcpdump抓包验证
sudo tcpdump -i any -nn host proxy.example.com and port 3128

各方案性能对比

客户端类型 连接建立时间 吞吐量 适用场景
HttpURLConnection 150ms 1200/s 简单低频请求
Apache HttpClient 5 80ms 3500/s 高并发生产环境
OkHttp 3 65ms 4000/s 移动端/高频调用
RestTemplate 100ms 2500/s Spring生态整合

遇到代理认证失败或连接超时问题,可在评论区提交:

  1. 完整的异常堆栈信息
  2. 代理服务器类型(Squid/Nginx等)
  3. 使用的Java版本

将提供针对性的网络诊断建议和代码修复方案。

❤️❤️❤️本人水平有限,如有纰漏,欢迎各位大佬评论批评指正!

如果觉得这篇文对你有帮助的话,也请给个点赞、收藏下吧,非常感谢!

Stay Hungry Stay Foolish 道阻且长,行则将至,让我们一起加油吧!

你可能感兴趣的:(java,http,开发语言)