杰瑞科技汇

Java HTTPProxy如何配置与使用?

Of course! Here is a comprehensive guide on how to use an HTTP proxy in Java, covering the most common approaches for both standard Java and popular libraries like Apache HttpClient and OkHttp.

Java HTTPProxy如何配置与使用?-图1
(图片来源网络,侵删)

What is an HTTP Proxy?

An HTTP proxy is a server that acts as an intermediary between your client application (your Java code) and the target server you want to communicate with. All your web requests are sent to the proxy, which then forwards them to the destination and sends the response back to you.

Common Use Cases:

  • Bypassing Network Restrictions: Accessing resources from a restricted network.
  • Anonymity: Hiding your IP address.
  • Caching: Storing copies of frequently accessed resources to speed up subsequent requests.
  • Content Filtering: Blocking or modifying web content.
  • Security: Inspecting and logging all outgoing traffic.

Method 1: Using Standard Java (java.net.HttpURLConnection)

This is the most basic approach, built into the Java Standard Library. It's simple but less flexible than dedicated HTTP client libraries.

How to Set the Proxy

You configure the proxy using system properties. These properties affect all HttpURLConnection instances created within the same JVM.

Java HTTPProxy如何配置与使用?-图2
(图片来源网络,侵删)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
public class StandardJavaProxy {
    public static void main(String[] args) {
        // 1. Define your proxy details
        String proxyHost = "your.proxy.com"; // e.g., "proxy.example.com"
        int proxyPort = 8080;               // e.g., 8080
        // 2. Set the system properties for the proxy
        // This will affect all HttpURLConnections in this JVM.
        System.setProperty("http.proxyHost", proxyHost);
        System.setProperty("http.proxyPort", String.valueOf(proxyPort));
        // For HTTPS requests, you should also set the HTTPS proxy
        System.setProperty("https.proxyHost", proxyHost);
        System.setProperty("https.proxyPort", String.valueOf(proxyPort));
        // Optional: If your proxy requires authentication
        // System.setProperty("http.proxyUser", "username");
        // System.setProperty("http.proxyPassword", "password");
        String targetUrl = "http://httpbin.org/ip"; // A service that returns your IP address
        try {
            URL url = new URL(targetUrl);
            // The HttpURLConnection will now automatically use the proxy defined by the system properties.
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // Set request method
            connection.setRequestMethod("GET");
            // Get the response code
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            // Read the response
            if (responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                // Print the response, which should show the proxy's IP
                System.out.println("Response from server:");
                System.out.println(response.toString());
            } else {
                System.out.println("GET request failed.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Pros:

  • No external dependencies.
  • Simple for basic use cases.

Cons:

  • Affects the entire JVM, which can be undesirable in complex applications.
  • Lacks advanced features like connection pooling, asynchronous requests, and fine-grained control.
  • Proxy authentication is handled by the system properties, which can be clunky.

Method 2: Using Apache HttpClient (Recommended)

Apache HttpClient is a powerful, feature-rich library for HTTP communication. It provides much more control and flexibility than the standard library.

Step 1: Add Dependency

You need to add the HttpClient dependency to your project (e.g., in your pom.xml for Maven).

Java HTTPProxy如何配置与使用?-图3
(图片来源网络,侵删)
<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.3.1</version> <!-- Use the latest version -->
</dependency>

Step 2: Configure and Use the Proxy

With HttpClient, you configure the proxy for each specific HttpClient instance, which is much cleaner.

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.net.InetAddressUtils;
import org.apache.hc.core5.util.Timeout;
import java.io.IOException;
import java.net.InetSocketAddress;
public class ApacheHttpClientProxy {
    public static void main(String[] args) {
        // 1. Define your proxy details
        String proxyHost = "your.proxy.com";
        int proxyPort = 8080;
        // For authentication
        String proxyUser = "username";
        String proxyPassword = "password";
        // 2. Create a proxy address
        InetSocketAddress proxyAddress = new InetSocketAddress(proxyHost, proxyPort);
        // 3. Configure the request to use the proxy
        RequestConfig config = RequestConfig.custom()
                .setProxy(proxyAddress)
                .setConnectTimeout(Timeout.ofSeconds(10))
                .build();
        // 4. Create HttpClient with the proxy configuration
        try (CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(config)
                .build()) {
            HttpGet request = new HttpGet("http://httpbin.org/ip");
            // 5. Execute the request
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                System.out.println("Response Code: " + response.getCode());
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    // 6. Read and print the response
                    String result = EntityUtils.toString(entity);
                    System.out.println("Response from server:");
                    System.out.println(result);
                    EntityUtils.consume(entity); // Ensure the entity is fully consumed
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Handling Proxy Authentication (Apache HttpClient)

If your proxy requires a username and password, you need to use a CredentialsProvider.

// Add this to the ApacheHttpClientProxy example
import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.protocol.HttpContext;
// Inside the main method, before creating the HttpClient
// Create a credentials provider
BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
        new HttpHost(proxyHost, proxyPort), // The proxy realm
        new UsernamePasswordCredentials(proxyUser, proxyPassword.toCharArray()));
// Build the HttpClient with the credentials provider
try (CloseableHttpClient httpClient = HttpClients.custom()
        .setDefaultRequestConfig(config) // The config with the proxy address
        .setDefaultCredentialsProvider(credsProvider)
        .build()) {
    // ... rest of the code to execute the request
}

Method 3: Using OkHttp

OkHttp is another extremely popular and modern HTTP client, especially known for its ease of use and performance on Android. It's also a great choice for server-side Java.

Step 1: Add Dependency

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.12.0</version> <!-- Use the latest version -->
</dependency>

Step 2: Configure and Use the Proxy

OkHttp makes using a proxy very straightforward with its OkHttpClient.Builder.

import okhttp3.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
public class OkHttpProxyExample {
    public static void main(String[] args) {
        // 1. Define your proxy details
        String proxyHost = "your.proxy.com";
        int proxyPort = 8080;
        // For authentication
        String proxyUser = "username";
        String proxyPassword = "password";
        // 2. Create a Proxy object
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        // 3. Build the OkHttpClient with the proxy
        OkHttpClient client = new OkHttpClient.Builder()
                .proxy(proxy)
                // For authentication, you can use an Authenticator
                .proxyAuthenticator((route, response) -> {
                    String credential = Credentials.basic(proxyUser, proxyPassword);
                    return response.request().newBuilder()
                            .header("Proxy-Authorization", credential)
                            .build();
                })
                .build();
        // 4. Create a request
        Request request = new Request.Builder()
                .url("http://httpbin.org/ip")
                .build();
        // 5. Execute the request
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            // 6. Get and print the response
            System.out.println("Response Code: " + response.code());
            System.out.println("Response from server:");
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Summary and Comparison

Feature Standard Java (HttpURLConnection) Apache HttpClient OkHttp
Dependency None (Built-in) httpclient5 okhttp
Ease of Use Simple, but limited. Good, very configurable. Excellent, very fluent API.
Flexibility Low. Affects entire JVM. High. Per-instance configuration. High. Per-instance configuration.
Features Basic HTTP/HTTPS. Advanced: Connection pooling, async, interceptors, auth. Advanced: Connection pooling, async, websockets, interceptors.
Proxy Control System properties (global). RequestConfig on HttpClient builder. Proxy object on OkHttpClient builder.
Proxy Auth System properties (clunky). CredentialsProvider. Authenticator.
Recommendation For simple scripts or when no libraries are allowed. For enterprise applications requiring robustness and control. For modern applications, Android, or when a simple, powerful API is preferred.

For any serious application, Apache HttpClient or OkHttp are the recommended choices due to their superior flexibility, performance, and feature set.

分享:
扫描分享到社交APP
上一篇
下一篇