Java Code Examples for java.net.Proxy.Type#HTTP

The following examples show how to use java.net.Proxy.Type#HTTP . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractWeixinmpController.java    From weixinmp4java with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化HTTP代理服务器
 */
private void initHttpProxy() {
    // 初始化代理服务器
    if (httpProxyHost != null && httpProxyPort != null) {
        SocketAddress sa = new InetSocketAddress(httpProxyHost, httpProxyPort);
        proxy = new Proxy(Type.HTTP, sa);
        // 初始化代理服务器的用户验证
        if (httpProxyUsername != null && httpProxyPassword != null) {
            Authenticator.setDefault(new Authenticator() {

                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(httpProxyUsername, httpProxyPassword.toCharArray());
                }
            });
        }

    }
}
 
Example 2
Source File: AbstractWeixinmpController.java    From weixinmp4java with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化HTTP代理服务器
 */
private void initHttpProxy() {
    // 初始化代理服务器
    if (httpProxyHost != null && httpProxyPort != null) {
        SocketAddress sa = new InetSocketAddress(httpProxyHost, httpProxyPort);
        proxy = new Proxy(Type.HTTP, sa);
        // 初始化代理服务器的用户验证
        if (httpProxyUsername != null && httpProxyPassword != null) {
            Authenticator.setDefault(new Authenticator() {

                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(httpProxyUsername, httpProxyPassword.toCharArray());
                }
            });
        }

    }
}
 
Example 3
Source File: HttpClientService.java    From cppcheclipse with Apache License 2.0 6 votes vote down vote up
private Proxy getProxyFromProxyData(IProxyData proxyData) throws UnknownHostException {
	
	Type proxyType;
	if (IProxyData.HTTP_PROXY_TYPE.equals(proxyData.getType())) {
		proxyType = Type.HTTP;
	} else if (IProxyData.SOCKS_PROXY_TYPE.equals(proxyData.getType())) {
		proxyType = Type.SOCKS;
	} else if (IProxyData.HTTPS_PROXY_TYPE.equals(proxyData.getType())) {
		proxyType = Type.HTTP;
	} else {
		throw new IllegalArgumentException("Invalid proxy type " + proxyData.getType());
	}

	InetSocketAddress sockAddr = new InetSocketAddress(InetAddress.getByName(proxyData.getHost()), proxyData.getPort());
	Proxy proxy = new Proxy(proxyType, sockAddr);
	if (!Strings.isNullOrEmpty(proxyData.getUserId())) {
		Authenticator.setDefault(new ProxyAuthenticator(proxyData.getUserId(), proxyData.getPassword()));  
	}
	return proxy;
}
 
Example 4
Source File: PollingStatusServiceImpl.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
private Proxy getProxy(URI uri) {
  if (proxyService == null) {
    return Proxy.NO_PROXY;
  }
  IProxyData[] proxies = proxyService.select(uri);
  for (IProxyData proxyData : proxies) {
    switch (proxyData.getType()) {
      case IProxyData.HTTPS_PROXY_TYPE:
      case IProxyData.HTTP_PROXY_TYPE:
        return new Proxy(
            Type.HTTP, new InetSocketAddress(proxyData.getHost(), proxyData.getPort()));
      case IProxyData.SOCKS_PROXY_TYPE:
        return new Proxy(
            Type.SOCKS, new InetSocketAddress(proxyData.getHost(), proxyData.getPort()));
      default:
        logger.warning("Unknown proxy-data type: " + proxyData.getType()); //$NON-NLS-1$
        break;
    }
  }
  return Proxy.NO_PROXY;
}
 
Example 5
Source File: ProxyFactory.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
public Proxy createProxy(URI uri) {
  Preconditions.checkNotNull(uri, "uri is null");
  Preconditions.checkArgument(!"http".equals(uri.getScheme()), "http is not a supported schema");

  IProxyService proxyServiceCopy = proxyService;
  if (proxyServiceCopy == null) {
    return Proxy.NO_PROXY;
  }

  IProxyData[] proxyDataForUri = proxyServiceCopy.select(uri);
  for (final IProxyData iProxyData : proxyDataForUri) {
    switch (iProxyData.getType()) {
      case IProxyData.HTTPS_PROXY_TYPE:
        return new Proxy(Type.HTTP, new InetSocketAddress(iProxyData.getHost(),
                                                          iProxyData.getPort()));
      case IProxyData.SOCKS_PROXY_TYPE:
        return new Proxy(Type.SOCKS, new InetSocketAddress(iProxyData.getHost(),
                                                           iProxyData.getPort()));
      default:
        logger.warning("Unsupported proxy type: " + iProxyData.getType());
        break;
    }
  }
  return Proxy.NO_PROXY;
}
 
Example 6
Source File: DefaultClientTest.java    From feign with Apache License 2.0 5 votes vote down vote up
/**
 * Test that the proxy is being used, but don't check the credentials. Credentials can still be
 * used, but they must be set using the appropriate system properties and testing that is not what
 * we are looking to do here.
 */
@Test
public void canCreateWithImplicitOrNoCredentials() throws Exception {
  Proxied proxied = new Proxied(
      TrustingSSLSocketFactory.get(), null,
      new Proxy(Type.HTTP, proxyAddress));
  assertThat(proxied).isNotNull();
  assertThat(proxied.getCredentials()).isNullOrEmpty();

  /* verify that the proxy */
  HttpURLConnection connection = proxied.getConnection(new URL("http://www.example.com"));
  assertThat(connection).isNotNull().isInstanceOf(HttpURLConnection.class);
}
 
Example 7
Source File: HttpUtil.java    From socialauth with MIT License 5 votes vote down vote up
/**
 * 
 * Sets the proxy host and port. This will be implicitly called if
 * "proxy.host" and "proxy.port" properties are given in properties file
 * 
 * @param host
 *            proxy host
 * @param port
 *            proxy port
 */
public static void setProxyConfig(final String host, final int port) {
	if (host != null) {
		int proxyPort = port;
		if (proxyPort < 0) {
			proxyPort = 0;
		}
		LOG.debug("Setting proxy - Host : " + host + "   port : " + port);
		proxyObj = new Proxy(Type.HTTP, new InetSocketAddress(host, port));
	}
}
 
Example 8
Source File: RequestFactoryLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Before
public void setUp() {
    Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(PROXY_SERVER_HOST, PROXY_SERVER_PORT));

    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    requestFactory.setProxy(proxy);

    restTemplate = new RestTemplate(requestFactory);
}
 
Example 9
Source File: ProxyConfig.java    From importer-exporter with Apache License 2.0 5 votes vote down vote up
public Proxy toProxy() {
	if (hasValidProxySettings()) {
		switch (type) {
		case HTTP:
		case HTTPS:
			return new Proxy(Type.HTTP, new InetSocketAddress(host, port));
		case SOCKS:
			return new Proxy(Type.SOCKS, new InetSocketAddress(host, port));
		}
	}

	return null;
}
 
Example 10
Source File: MasterServerConfig.java    From seventh with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @return the proxy settings
 */
public Proxy getProxy() {        
    LeoObject proxy = this.config.get("master_server", "proxy_settings");
    if(LeoObject.isTrue(proxy)) {
        Proxy p = new Proxy(Type.HTTP, new InetSocketAddress(this.config.getString("master_server", "proxy_settings", "address"), 
                                                             this.config.getInt(88, "master_server", "proxy_settings", "port")));
        
        return (p);
    }
    
    return Proxy.NO_PROXY;
}
 
Example 11
Source File: Helper.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
private static Proxy getProxy ( final String url )
{
    final ProxySelector ps = ProxySelector.getDefault ();
    if ( ps == null )
    {
        logger.debug ( "No proxy selector found" );
        return null;
    }

    final List<java.net.Proxy> proxies = ps.select ( URI.create ( url ) );
    for ( final java.net.Proxy proxy : proxies )
    {
        if ( proxy.type () != Type.HTTP )
        {
            logger.debug ( "Unsupported proxy type: {}", proxy.type () );
            continue;
        }

        final SocketAddress addr = proxy.address ();
        logger.debug ( "Proxy address: {}", addr );

        if ( ! ( addr instanceof InetSocketAddress ) )
        {
            logger.debug ( "Unsupported proxy address type: {}", addr.getClass () );
            continue;
        }

        final InetSocketAddress inetAddr = (InetSocketAddress)addr;

        return new Proxy ( Proxy.TYPE_HTTP, inetAddr.getHostString (), inetAddr.getPort () );
    }

    logger.debug ( "No proxy found" );
    return null;
}
 
Example 12
Source File: TimeoutAwareConnectionFactoryTest.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@Test
public void testConstructorWithProxyAndTimeouts() throws MalformedURLException, IOException {
  Proxy proxy =
      new Proxy(Type.HTTP,
                new InetSocketAddress(proxyServer.getHostname(), proxyServer.getPort()));
  HttpURLConnection connection =
      new TimeoutAwareConnectionFactory(proxy, 1764, 3528)
          .openConnection(new URL(NONEXISTENTDOMAIN));
  connectReadAndDisconnect(connection);
  assertThat(connection.getConnectTimeout(), is(1764));
  assertThat(connection.getReadTimeout(), is(3528));
}
 
Example 13
Source File: TimeoutAwareConnectionFactoryTest.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@Test
public void testConstructorWithProxy() throws MalformedURLException, IOException {
  Proxy proxy =
      new Proxy(Type.HTTP,
                new InetSocketAddress(proxyServer.getHostname(), proxyServer.getPort()));
  HttpURLConnection connection =
      new TimeoutAwareConnectionFactory(proxy).openConnection(new URL(NONEXISTENTDOMAIN));
  connectReadAndDisconnect(connection);
}
 
Example 14
Source File: WebUtils.java    From alipay-sdk with Apache License 2.0 5 votes vote down vote up
private static HttpURLConnection getConnection(URL url, String method, String ctype,
                                               String proxyHost, int proxyPort) throws IOException {
    Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
    return getConnection(url, method, ctype, proxy);
}
 
Example 15
Source File: DefaultClientTest.java    From feign with Apache License 2.0 5 votes vote down vote up
@Test
public void canCreateWithExplicitCredentials() throws Exception {
  Proxied proxied = new Proxied(
      TrustingSSLSocketFactory.get(), null,
      new Proxy(Type.HTTP, proxyAddress), "user", "password");
  assertThat(proxied).isNotNull();
  assertThat(proxied.getCredentials()).isNotBlank();

  HttpURLConnection connection = proxied.getConnection(new URL("http://www.example.com"));
  assertThat(connection).isNotNull().isInstanceOf(HttpURLConnection.class);
}
 
Example 16
Source File: Processor.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private HttpURLConnection openConnection ( final URL url ) throws IOException
{
    final String host = this.properties.getProperty ( "local.proxy.host" );
    final String port = this.properties.getProperty ( "local.proxy.port" );

    if ( host != null && port != null && !host.isEmpty () && !port.isEmpty () )
    {
        final Proxy proxy = new Proxy ( Type.HTTP, new InetSocketAddress ( host, Integer.parseInt ( port ) ) );
        return (HttpURLConnection)url.openConnection ( proxy );
    }
    else
    {
        return (HttpURLConnection)url.openConnection ();
    }
}
 
Example 17
Source File: HttpRequest.java    From letv with Apache License 2.0 4 votes vote down vote up
private Proxy createProxy() {
    return new Proxy(Type.HTTP, new InetSocketAddress(this.httpProxyHost, this.httpProxyPort));
}
 
Example 18
Source File: RSSocketFactory.java    From Game with GNU General Public License v3.0 4 votes vote down vote up
private Socket open(Proxy proxy) throws IOException {
	try {
		if (proxy.type() != Type.DIRECT) {
			SocketAddress var3 = proxy.address();
			if (var3 instanceof InetSocketAddress) {
				InetSocketAddress var4 = (InetSocketAddress) var3;
				if (proxy.type() == Type.HTTP) {
					String var16 = null;

					try {
						Class<?> var6 = Class.forName("sun.net.www.protocol.http.AuthenticationInfo");
						Method var7 = var6.getDeclaredMethod("getProxyAuth",
							String.class, Integer.TYPE);
						var7.setAccessible(true);
						Object var8 = var7.invoke(null,
							var4.getHostName(), valueOf(var4.getPort()));
						if (null != var8) {
							Method var9 = var6.getDeclaredMethod("supportsPreemptiveAuthorization");
							var9.setAccessible(true);
							if ((Boolean) var9.invoke(var8, new Object[0])) {
								Method var10 = var6.getDeclaredMethod("getHeaderName");
								var10.setAccessible(true);
								Method var11 = var6.getDeclaredMethod("getHeaderValue",
									URL.class, String.class);
								var11.setAccessible(true);
								String var12 = (String) var10.invoke(var8, new Object[0]);
								String var13 = (String) var11.invoke(var8,
									new Object[]{new URL("https://" + this.socketHost + "/"), "https"});
								var16 = var12 + ": " + var13;
							}
						}
					} catch (Exception ignored) {
					}

					return this.openConnect(var4.getPort(), 1514, var16, var4.getHostName());
				} else if (proxy.type() != Type.SOCKS) {
					return null;
				} else {
					Socket var5 = new Socket(proxy);
					var5.connect(new InetSocketAddress(this.socketHost, this.socketPort));
					return var5;
				}
			} else {
				return null;
			}
		} else {
			return this.openRaw();
		}
	} catch (RuntimeException var15) {
		throw GenUtil.makeThrowable(var15,
			"gb.F(" + (proxy != null ? "{...}" : "null") + ',' + "dummy" + ')');
	}
}
 
Example 19
Source File: WebUtils.java    From alipay-sdk-java-all with Apache License 2.0 4 votes vote down vote up
public static HttpURLConnection getConnection(URL url, String method, String ctype,
                                              String proxyHost, int proxyPort) throws IOException {
    Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
    return getConnection(url, method, ctype, proxy);
}
 
Example 20
Source File: InvokeHTTP.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@OnScheduled
public void setUpClient(final ProcessContext context) throws IOException {
    okHttpClientAtomicReference.set(null);

    OkHttpClient okHttpClient = new OkHttpClient();

    // Add a proxy if set
    final String proxyHost = context.getProperty(PROP_PROXY_HOST).getValue();
    final Integer proxyPort = context.getProperty(PROP_PROXY_PORT).asInteger();
    if (proxyHost != null && proxyPort != null) {
        final Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        okHttpClient.setProxy(proxy);
    }

    // Set timeouts
    okHttpClient.setConnectTimeout((context.getProperty(PROP_CONNECT_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()), TimeUnit.MILLISECONDS);
    okHttpClient.setReadTimeout(context.getProperty(PROP_READ_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue(), TimeUnit.MILLISECONDS);

    // Set whether to follow redirects
    okHttpClient.setFollowRedirects(context.getProperty(PROP_FOLLOW_REDIRECTS).asBoolean());

    final SSLContextService sslService = context.getProperty(PROP_SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
    final SSLContext sslContext = sslService == null ? null : sslService.createSSLContext(ClientAuth.NONE);

    // check if the ssl context is set and add the factory if so
    if (sslContext != null) {
        okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());
    }

    // check the trusted hostname property and override the HostnameVerifier
    String trustedHostname = trimToEmpty(context.getProperty(PROP_TRUSTED_HOSTNAME).getValue());
    if (!trustedHostname.isEmpty()) {
        okHttpClient.setHostnameVerifier(new OverrideHostnameVerifier(trustedHostname, okHttpClient.getHostnameVerifier()));
    }

    setAuthenticator(okHttpClient, context);

    useChunked = context.getProperty(PROP_USE_CHUNKED_ENCODING).asBoolean();

    okHttpClientAtomicReference.set(okHttpClient);
}