下面列出了怎么用java.net.Proxy的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public Proxy make() {
if (super.proxyList==null || super.proxyList.size()==0) {
return null;
}
if (super.proxyList.size() == 1) {
super.proxyList.get(0);
}
int countVal = count.incrementAndGet();
if (countVal > 100000) {
countVal = 0;
count.set(countVal);
}
return super.proxyList.get(countVal%super.proxyList.size());
}
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(0);
(new Thread() {
@Override
public void run() { serve(); }
}).start();
Proxy socksProxy = new Proxy(Proxy.Type.SOCKS,
new InetSocketAddress(InetAddress.getLocalHost(), serverSocket.getLocalPort()));
test(socksProxy);
} catch (IOException e) {
unexpected(e);
} finally {
close(serverSocket);
if (failed > 0)
throw new RuntimeException("Test Failed: passed:" + passed + ", failed:" + failed);
}
}
private Registry<ConnectionSocketFactory> registry(final HttpObjectConfig config) {
final ProxyInfo proxyInfo = config.getExecution().getProxyInfo();
final boolean isSocksProxied = (proxyInfo != null && proxyInfo.getProxy().type() == Proxy.Type.SOCKS);
if (isSocksProxied) {
return RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", new SocksHttp(proxyInfo.getProxy()))
.register("https", new SocksHttps(proxyInfo.getProxy(), sslContext(config),
config.getExecution().getHostnameVerifier()))
.build();
} else {
return RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslContext(config), config.getExecution().getHostnameVerifier()))
.build();
}
}
/**
* @param protocol
* @return
* @throws OpenAS2Exception
* @deprecated - use post method to send messages
*/
private static Proxy getProxy(String protocol) throws OpenAS2Exception {
String proxyHost = Properties.getProperty(protocol + ".proxyHost", null);
if (proxyHost == null) {
proxyHost = System.getProperty(protocol + ".proxyHost");
}
if (proxyHost == null) {
return Proxy.NO_PROXY;
}
String proxyPort = Properties.getProperty(protocol + ".proxyPort", null);
if (proxyPort == null) {
proxyPort = System.getProperty(protocol + ".proxyPort");
}
if (proxyPort == null) {
throw new OpenAS2Exception("Missing PROXY port since Proxy host is set");
}
int port = Integer.parseInt(proxyPort);
return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, port));
}
public static InetSocketAddress
getProxyAddress(
InetSocketAddress target )
{
Proxy p = proxy_selector.getSOCKSProxy( DEFAULT_SOCKS_SERVER_ADDRESS, target );
// always use a proxy here as the calling code should know what it is doing...
if ( p.type() == Proxy.Type.SOCKS ){
SocketAddress sa = p.address();
if ( sa instanceof InetSocketAddress ){
return((InetSocketAddress)sa);
}
}
return( DEFAULT_SOCKS_SERVER_ADDRESS );
}
protected HttpURLConnection(URL u, Proxy p, Handler handler)
throws IOException {
super(checkURL(u));
requests = new MessageHeader();
responses = new MessageHeader();
userHeaders = new MessageHeader();
this.handler = handler;
instProxy = p;
if (instProxy instanceof sun.net.ApplicationProxy) {
/* Application set Proxies should not have access to cookies
* in a secure environment unless explicitly allowed. */
try {
cookieHandler = CookieHandler.getDefault();
} catch (SecurityException se) { /* swallow exception */ }
} else {
cookieHandler = java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<CookieHandler>() {
public CookieHandler run() {
return CookieHandler.getDefault();
}
});
}
cacheHandler = java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<ResponseCache>() {
public void open(
final String method,
final URL url,
boolean async,
final String userName,
final String password)
throws IOException {
this.abort();
Proxy proxy = this.proxy;
URLConnection c =
proxy == null || proxy == Proxy.NO_PROXY ? url.openConnection() : url.openConnection(proxy);
synchronized (this) {
this.connection = c;
this.async = async;
this.requestMethod = method;
this.requestURL = url;
this.requestUserName = userName;
this.requestPassword = password;
}
this.changeState(AjaxHttpRequest.STATE_LOADING, 0, null, null);
}
private static HttpURLConnection a(Context context, String str) {
try {
URL url = new URL(str);
if (context.getPackageManager().checkPermission(z[43], context.getPackageName()) == 0) {
NetworkInfo activeNetworkInfo = ((ConnectivityManager) context.getSystemService(z[44])).getActiveNetworkInfo();
if (!(activeNetworkInfo == null || activeNetworkInfo.getType() == 1)) {
String extraInfo = activeNetworkInfo.getExtraInfo();
if (extraInfo != null && (extraInfo.equals(z[40]) || extraInfo.equals(z[41]) || extraInfo.equals(z[42]))) {
return (HttpURLConnection) url.openConnection(new Proxy(Type.HTTP, new InetSocketAddress(z[45], 80)));
}
}
}
return (HttpURLConnection) url.openConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e2) {
e2.printStackTrace();
return null;
}
}
public void testAddAndSelect() {
MyProxySelector selector = new MyProxySelector();
assertNull(selector.getForType(MyProxyType.HTTP));
assertNull(selector.getForType(MyProxyType.SOCKS));
assertNull(selector.getForType(MyProxyType.FTP));
assertEquals(Proxy.NO_PROXY, selector.select(httpURI).get(0));
assertEquals(Proxy.NO_PROXY, selector.select(ftpURI).get(0));
assertEquals(Proxy.NO_PROXY, selector.select(svnURI).get(0));
final MyProxy http = new MyProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 8080)), MyProxyType.HTTP);
final MyProxy ftp = new MyProxy(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("hehe.kill.yourself", 8080)), MyProxyType.FTP);
final MyProxy socks = new MyProxy(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("localhost", 8080)), MyProxyType.SOCKS);
selector.add(http);
selector.add(ftp);
selector.add(socks);
assertNotNull(selector.getForType(MyProxyType.HTTP));
assertNotNull(selector.getForType(MyProxyType.SOCKS));
assertNotNull(selector.getForType(MyProxyType.FTP));
assertEquals(http.getProxy(), selector.select(httpURI).get(0));
assertEquals(ftp.getProxy(), selector.select(ftpURI).get(0));
assertEquals(socks.getProxy(), selector.select(svnURI).get(0));
}
public void XXXtestGetProxyAutoConfigWithLocalInvalidPAC() throws URISyntaxException {
List<String> pacFileLocations = new LinkedList<String>();
for (File pacFile : new File[] {
new File(getDataDir(), "pacFiles"),
//new File(getDataDir(), "doesNotExist")
}) {
pacFileLocations.add(pacFile.getAbsolutePath());
pacFileLocations.add("file://" + pacFile.getAbsolutePath());
pacFileLocations.add(pacFile.toURI().toString());
}
for (String pacFileLoc : pacFileLocations) {
ProxyAutoConfig pac = ProxyAutoConfig.get(pacFileLoc);
assertNotNull(pac);
URI uri = pac.getPacURI();
assertNotNull(uri);
List<Proxy> proxies = pac.findProxyForURL(new URI("http://netbeans.org"));
assertEquals(1, proxies.size());
assertEquals("DIRECT", proxies.get(0).toString());
}
}
private void setProxy(OkHttpClient.Builder builder) {
ProxyConfiguration config = proxyConfigurationService.getConfiguration();
if (!config.getProxyType().equals(Proxy.Type.DIRECT)) {
final Proxy proxy = config.createProxy();
builder.proxy(proxy);
if (config.hasCredential()){
builder.proxyAuthenticator((route, response) -> {
final String credential= Credentials.basic(config.getProxyUserName(), config.getProxyUserPassword());
return response.request().newBuilder()
.header("Proxy-Authorization", credential)
.build();
});
}
}
}
/** Returns the next proxy to try. May be PROXY.NO_PROXY but never null. */
private Proxy nextProxy() {
// If the user specifies a proxy, try that and only that.
if (userSpecifiedProxy != null) {
hasNextProxy = false;
return userSpecifiedProxy;
}
// Try each of the ProxySelector choices until one connection succeeds. If none succeed
// then we'll try a direct connection below.
if (proxySelectorProxies != null) {
while (proxySelectorProxies.hasNext()) {
Proxy candidate = proxySelectorProxies.next();
if (candidate.type() != Proxy.Type.DIRECT) {
return candidate;
}
}
}
// Finally try a direct connection.
hasNextProxy = false;
return Proxy.NO_PROXY;
}
DelegateHttpsURLConnection(URL url, Proxy p,
sun.net.www.protocol.http.Handler handler,
com.sun.net.ssl.HttpsURLConnection httpsURLConnection)
throws IOException {
super(url, p, handler);
this.httpsURLConnection = httpsURLConnection;
}
public Address(String uriHost, int uriPort, SSLSocketFactory sslSocketFactory,
HostnameVerifier hostnameVerifier, OkAuthenticator authenticator, Proxy proxy,
List<String> transports) throws UnknownHostException {
if (uriHost == null) throw new NullPointerException("uriHost == null");
if (uriPort <= 0) throw new IllegalArgumentException("uriPort <= 0: " + uriPort);
if (authenticator == null) throw new IllegalArgumentException("authenticator == null");
if (transports == null) throw new IllegalArgumentException("transports == null");
this.proxy = proxy;
this.uriHost = uriHost;
this.uriPort = uriPort;
this.sslSocketFactory = sslSocketFactory;
this.hostnameVerifier = hostnameVerifier;
this.authenticator = authenticator;
this.transports = Util.immutableList(transports);
}
protected HttpClient getNewHttpClient(URL url, Proxy p, int connectTimeout,
boolean useCache)
throws IOException {
return HttpsClient.New(getSSLSocketFactory(), url,
getHostnameVerifier(), p,
useCache, connectTimeout, this);
}
private static URLConnection connect(URL url, Duration readTimeout, Duration connectTimeout,
@Nullable Proxy proxy) throws IOException {
URLConnection connection = (proxy != null) ? url.openConnection(proxy) : url.openConnection();
connection.setConnectTimeout(Math.toIntExact(connectTimeout.toMillis()));
connection.setReadTimeout(Math.toIntExact(readTimeout.toMillis()));
return connection;
}
@Override
public void setProxy(FTPClient client, String system, AppService myResponse) {
String proxyHost = parameterService.getParameterStringByKey("cerberus_proxy_host", "",
DEFAULT_PROXY_HOST);
int proxyPort = parameterService.getParameterIntegerByKey("cerberus_proxy_port", "",
DEFAULT_PROXY_PORT);
myResponse.setProxy(true);
myResponse.setProxyHost(proxyHost);
myResponse.setProxyPort(proxyPort);
SocketAddress proxyAddr = new InetSocketAddress(proxyHost, proxyPort);
Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyAddr);
if (parameterService.getParameterBooleanByKey("cerberus_proxyauthentification_active", system,
DEFAULT_PROXYAUTHENT_ACTIVATE)) {
Authenticator.setDefault(
new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
String proxyUser = parameterService.getParameterStringByKey("cerberus_proxyauthentification_user", "", DEFAULT_PROXYAUTHENT_USER);
String proxyPassword = parameterService.getParameterStringByKey("cerberus_proxyauthentification_password", "", DEFAULT_PROXYAUTHENT_PASSWORD);
myResponse.setProxyWithCredential(true);
myResponse.setProxyUser(proxyUser);
return new PasswordAuthentication(
proxyUser, proxyPassword.toCharArray()
);
}
}
);
}
client.setProxy(proxy);
}
void test() throws Exception {
InetSocketAddress proxyAddress = new InetSocketAddress(proxyHost, proxyPort);
Proxy httpProxy = new Proxy(Proxy.Type.HTTP, proxyAddress);
try (ServerSocket ss = new ServerSocket(0);
Socket sock = new Socket(httpProxy)) {
sock.setSoTimeout(SO_TIMEOUT);
sock.setTcpNoDelay(false);
InetSocketAddress externalAddress =
new InetSocketAddress(InetAddress.getLocalHost(), ss.getLocalPort());
out.println("Trying to connect to server socket on " + externalAddress);
sock.connect(externalAddress);
try (Socket externalSock = ss.accept()) {
// perform some simple checks
check(sock.isBound(), "Socket is not bound");
check(sock.isConnected(), "Socket is not connected");
check(!sock.isClosed(), "Socket should not be closed");
check(sock.getSoTimeout() == SO_TIMEOUT,
"Socket should have a previously set timeout");
check(sock.getTcpNoDelay() == false, "NODELAY should be false");
simpleDataExchange(sock, externalSock);
}
}
}
/** Resets {@link #nextProxy} to the first option. */
private void resetNextProxy(URI uri, Proxy proxy) {
this.hasNextProxy = true; // This includes NO_PROXY!
if (proxy != null) {
this.userSpecifiedProxy = proxy;
} else {
List<Proxy> proxyList = proxySelector.select(uri);
if (proxyList != null) {
this.proxySelectorProxies = proxyList.iterator();
}
}
}
private HttpURLConnection open(URL url, Proxy proxy) {
OkHttpClient newClient = mClient.newBuilder().proxy(proxy).build();
String protocol = url.getProtocol();
if (protocol.equalsIgnoreCase("http")) return new OkHttpURLConnection(url, newClient);
if (protocol.equalsIgnoreCase("https")) return new OkHttpsURLConnection(url, newClient);
throw new IllegalArgumentException("Unexpected protocol: " + protocol);
}
@Test(groups = "unit")
public void testSocksOverIPv6() throws Exception {
if (!shouldRun) return;
Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("::1",
socks.getPort()));
URL url = new URL("http://[::1]:" + server.getAddress().getPort());
java.net.URLConnection conn = url.openConnection(proxy);
String actual = "";
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()))) {
actual = reader.readLine();
}
assertEquals(actual, response);
}
/** Resets {@link #nextProxy} to the first option. */
private void resetNextProxy(URI uri, Proxy proxy) {
this.hasNextProxy = true; // This includes NO_PROXY!
if (proxy != null) {
this.userSpecifiedProxy = proxy;
} else {
List<Proxy> proxyList = proxySelector.select(uri);
if (proxyList != null) {
this.proxySelectorProxies = proxyList.iterator();
}
}
}
@OnEnabled
public void setConfiguredValues(final ConfigurationContext context) {
configuration = new ProxyConfiguration();
configuration.setProxyType(Proxy.Type.valueOf(context.getProperty(PROXY_TYPE).getValue()));
configuration.setProxyServerHost(context.getProperty(PROXY_SERVER_HOST).evaluateAttributeExpressions().getValue());
configuration.setProxyServerPort(context.getProperty(PROXY_SERVER_PORT).evaluateAttributeExpressions().asInteger());
configuration.setProxyUserName(context.getProperty(PROXY_USER_NAME).evaluateAttributeExpressions().getValue());
configuration.setProxyUserPassword(context.getProperty(PROXY_USER_PASSWORD).evaluateAttributeExpressions().getValue());
}
void run() {
System.out.printf("urlhost=%s properties=%s: proxied? %s%n",
urlhost, localProperties, expectedProxying);
List<Proxy> proxies = withSystemPropertiesSet(localProperties,
() -> ProxySelector.getDefault().select(
URI.create(urlhost))
);
verify(proxies);
}
public SmartQQApi(Proxy proxy) {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.cookieJar(cookieJar);
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
if (proxy != null) {
builder.proxy(proxy);
}
this.client = builder.build();
}
@Override
public void afterPropertiesSet() throws IllegalArgumentException {
Assert.notNull(this.type, "Property 'type' is required");
Assert.notNull(this.hostname, "Property 'hostname' is required");
if (this.port < 0 || this.port > 65535) {
throw new IllegalArgumentException("Property 'port' value out of range: " + this.port);
}
SocketAddress socketAddress = new InetSocketAddress(this.hostname, this.port);
this.proxy = new Proxy(this.type, socketAddress);
}
public Route(Address address, Proxy proxy, InetSocketAddress inetSocketAddress,
boolean modernTls) {
if (address == null) throw new NullPointerException("address == null");
if (proxy == null) throw new NullPointerException("proxy == null");
if (inetSocketAddress == null) throw new NullPointerException("inetSocketAddress == null");
this.address = address;
this.proxy = proxy;
this.inetSocketAddress = inetSocketAddress;
this.modernTls = modernTls;
}
DelegateHttpsURLConnection(URL url, Proxy p,
sun.net.www.protocol.http.Handler handler,
javax.net.ssl.HttpsURLConnection httpsURLConnection)
throws IOException {
super(url, p, handler);
this.httpsURLConnection = httpsURLConnection;
}
DelegateHttpsURLConnection(URL url, Proxy p,
sun.net.www.protocol.http.Handler handler,
javax.net.ssl.HttpsURLConnection httpsURLConnection)
throws IOException {
super(url, p, handler);
this.httpsURLConnection = httpsURLConnection;
}
public Route(Address address, Proxy proxy, InetSocketAddress inetSocketAddress) {
if (address == null) {
throw new NullPointerException("address == null");
}
if (proxy == null) {
throw new NullPointerException("proxy == null");
}
if (inetSocketAddress == null) {
throw new NullPointerException("inetSocketAddress == null");
}
this.address = address;
this.proxy = proxy;
this.inetSocketAddress = inetSocketAddress;
}