# Java Proxy Network Configuration
Here's a comprehensive guide to using proxy networks in Java for accessing the internet:
## 1. Basic Proxy Setup
### System-wide Proxy Settings
```java
public class SystemProxySetup {
public static void main(String[] args) {
// Set proxy settings system-wide
System.setProperty("http.proxyHost", "proxy.example.com");
System.setProperty("http.proxyPort", "8080");
System.setProperty("https.proxyHost", "proxy.example.com");
System.setProperty("https.proxyPort", "8080");
// For authenticated proxies
System.setProperty("http.proxyUser", "username");
System.setProperty("http.proxyPassword", "password");
// Make a test connection
try {
URL url = new URL("http://example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
System.out.println("Response Code: " + conn.getResponseCode());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
## 2. Connection-specific Proxy
```java
import java.net.*;
public class ConnectionSpecificProxy {
public static void main(String[] args) {
Proxy proxy = new Proxy(Proxy.Type.HTTP,
new InetSocketAddress("proxy.example.com", 8080));
try {
URL url = new URL("http://example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
// For authenticated proxies
String auth = "username:password";
String encodedAuth = java.util.Base64.getEncoder().encodeToString(auth.getBytes());
conn.setRequestProperty("Proxy-Authorization", "Basic " + encodedAuth);
System.out.println("Response Code: " + conn.getResponseCode());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
## 3. SOCKS Proxy Example
```java
import java.net.*;
public class SocksProxyExample {
public static void main(String[] args) {
// Set SOCKS proxy
System.setProperty("socksProxyHost", "socks.example.com");
System.setProperty("socksProxyPort", "1080");
// For authenticated SOCKS proxies (Java 9+)
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password".toCharArray());
}
});
try {
URL url = new URL("http://example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
System.out.println("Response Code: " + conn.getResponseCode());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
## 4. Proxy Selector (Advanced)
```java
import java.net.*;
import java.util.*;
public class CustomProxySelector extends ProxySelector {
private final List<Proxy> proxies;
public CustomProxySelector(String proxyHost, int proxyPort) {
this.proxies = Collections.singletonList(
new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort))
);
}
@Override
public List<Proxy> select(URI uri) {
return proxies;
}
@Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
System.err.println("Connection to proxy failed: " + ioe.getMessage());
}
public static void main(String[] args) {
// Register custom proxy selector
ProxySelector.setDefault(new CustomProxySelector("proxy.example.com", 8080));
try {
URL url = new URL("http://example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
System.out.println("Response Code: " + conn.getResponseCode());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
## 5. Proxy with HttpClient (Java 11+)
```java
import java.net.*;
import java.net.http.*;
import java.time.Duration;
public class HttpClientProxy {
public static void main(String[] args) {
// Configure proxy
ProxySelector proxySelector = new CustomProxySelector("proxy.example.com", 8080);
// Create HttpClient with proxy
HttpClient client = HttpClient.newBuilder()
.proxy(proxySelector)
.connectTimeout(Duration.ofSeconds(10))
.build();
// Create request
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.com"))
.timeout(Duration.ofSeconds(10))
.build();
try {
// Send request
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
System.out.println("Status Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
## 6. Proxy Authentication with Authenticator
```java
import java.net.*;
public class ProxyAuthenticator {
public static void main(String[] args) {
// Set proxy properties
System.setProperty("http.proxyHost", "proxy.example.com");
System.setProperty("http.proxyPort", "8080");
// Set authenticator
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (getRequestorType() == RequestorType.PROXY) {
return new PasswordAuthentication(
"username",
"password".toCharArray()
);
}
return null;
}
});
try {
URL url = new URL("http://example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
System.out.println("Response Code: " + conn.getResponseCode());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
## Key Considerations:
1. **Proxy Types**:
- HTTP proxies (`Proxy.Type.HTTP`)
- SOCKS proxies (`Proxy.Type.SOCKS`)
- Direct connection (`Proxy.NO_PROXY`)
2. **Authentication**:
- Basic authentication is most common
- NTLM authentication requires additional libraries
- Consider security when handling credentials
3. **Performance**:
- Reuse proxy connections when possible
- Consider connection pooling for multiple requests
4. **Error Handling**:
- Always handle connection failures
- Implement fallback mechanisms when proxies fail
5. **Security**:
- Use HTTPS for sensitive data
- Validate proxy certificates
- Consider using environment variables for credentials
Would you like me to focus on any specific aspect of proxy usage in Java, such as rotating proxies, proxy chaining, or handling specific authentication schemes?
No comments:
Post a Comment