Java Code Examples for java.net.Proxy

The following are top voted examples for showing how to use java.net.Proxy. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: owa-notifier   File: RestfullAcessProxy.java   View source code 8 votes vote down vote up
/**
 * Return a instance of tokenService to call it
 * 
 * @param authority
 * @return TokenService return a proxy to call api
 */
private static TokenService getRealTokenService(String authority) {
	// Create a logging interceptor to log request and responses
	OkHttpClient client = new OkHttpClient();
	InetSocketAddress p = findProxy();
	if(p != null) {
		client.setProxy(new Proxy(Proxy.Type.HTTP,p));
	} else { 
		client.setProxy(Proxy.NO_PROXY); 
	}
	// Create and configure the Retrofit object
	RestAdapter retrofit = new RestAdapter.Builder().setEndpoint(authority)
			.setLogLevel(LogLevel.FULL).setLog(new RestAdapter.Log() {
				@Override
				public void log(String msg) {
					logger.debug(msg);
				}
			}).setClient(new OkClient(client)).build();

	// Generate the token service
	return retrofit.create(TokenService.class);
}
 
Example 2
Project: GitHub   File: Address.java   View source code 7 votes vote down vote up
public Address(String uriHost, int uriPort, Dns dns, SocketFactory socketFactory,
    @Nullable SSLSocketFactory sslSocketFactory, @Nullable HostnameVerifier hostnameVerifier,
    @Nullable CertificatePinner certificatePinner, Authenticator proxyAuthenticator,
    @Nullable Proxy proxy, List<Protocol> protocols, List<ConnectionSpec> connectionSpecs,
    ProxySelector proxySelector) {
  this.url = new HttpUrl.Builder()
      .scheme(sslSocketFactory != null ? "https" : "http")
      .host(uriHost)
      .port(uriPort)
      .build();

  if (dns == null) throw new NullPointerException("dns == null");
  this.dns = dns;

  if (socketFactory == null) throw new NullPointerException("socketFactory == null");
  this.socketFactory = socketFactory;

  if (proxyAuthenticator == null) {
    throw new NullPointerException("proxyAuthenticator == null");
  }
  this.proxyAuthenticator = proxyAuthenticator;

  if (protocols == null) throw new NullPointerException("protocols == null");
  this.protocols = Util.immutableList(protocols);

  if (connectionSpecs == null) throw new NullPointerException("connectionSpecs == null");
  this.connectionSpecs = Util.immutableList(connectionSpecs);

  if (proxySelector == null) throw new NullPointerException("proxySelector == null");
  this.proxySelector = proxySelector;

  this.proxy = proxy;
  this.sslSocketFactory = sslSocketFactory;
  this.hostnameVerifier = hostnameVerifier;
  this.certificatePinner = certificatePinner;
}
 
Example 3
Project: GitHub   File: RealConnection.java   View source code 6 votes vote down vote up
/** Does all the work necessary to build a full HTTP or HTTPS connection on a raw socket. */
private void connectSocket(int connectTimeout, int readTimeout) throws IOException {
  Proxy proxy = route.proxy();
  Address address = route.address();

  rawSocket = proxy.type() == Proxy.Type.DIRECT || proxy.type() == Proxy.Type.HTTP
      ? address.socketFactory().createSocket()
      : new Socket(proxy);

  rawSocket.setSoTimeout(readTimeout);
  try {
    Platform.get().connectSocket(rawSocket, route.socketAddress(), connectTimeout);
  } catch (ConnectException e) {
    ConnectException ce = new ConnectException("Failed to connect to " + route.socketAddress());
    ce.initCause(e);
    throw ce;
  }
  source = Okio.buffer(Okio.source(rawSocket));
  sink = Okio.buffer(Okio.sink(rawSocket));
}
 
Example 4
Project: Backmemed   File: Manager.java   View source code 6 votes vote down vote up
public static Session loginPassword(String username, String password)
{
    if(username == null || username.length() <= 0 || password == null || password.length() <= 0)
        return null;

    YggdrasilAuthenticationService a = new YggdrasilAuthenticationService(Proxy.NO_PROXY, "");
    YggdrasilUserAuthentication b = (YggdrasilUserAuthentication)a.createUserAuthentication(Agent.MINECRAFT);
    b.setUsername(username);
    b.setPassword(password);
    try
    {
        b.logIn();
        return new Session(b.getSelectedProfile().getName(), b.getSelectedProfile().getId().toString(), b.getAuthenticatedToken(), "LEGACY");
    } catch (AuthenticationException e)
    {
    	altScreen.dispErrorString = "".concat("\247cBad Login \2477(").concat(username).concat(")");
        e.printStackTrace();
    }
    return null;
}
 
Example 5
Project: Proyecto-DASI   File: GradleStart.java   View source code 6 votes vote down vote up
private void attemptLogin(Map<String, String> argMap)
{
    YggdrasilUserAuthentication auth = (YggdrasilUserAuthentication) new YggdrasilAuthenticationService(Proxy.NO_PROXY, "1").createUserAuthentication(Agent.MINECRAFT);
    auth.setUsername(argMap.get("username"));
    auth.setPassword(argMap.get("password"));
    argMap.put("password", null);

    try {
        auth.logIn();
    }
    catch (AuthenticationException e)
    {
        LOGGER.error("-- Login failed!  " + e.getMessage());
        Throwables.propagate(e);
        return; // dont set other variables
    }

    LOGGER.info("Login Succesful!");
    argMap.put("accessToken", auth.getAuthenticatedToken());
    argMap.put("uuid", auth.getSelectedProfile().getId().toString().replace("-", ""));
    argMap.put("username", auth.getSelectedProfile().getName());
    argMap.put("userType", auth.getUserType().getName());
    
    // 1.8 only apperantly.. -_-
    argMap.put("userProperties", new GsonBuilder().registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()).create().toJson(auth.getUserProperties()));
}
 
Example 6
Project: afp-api-client   File: GetSomeAFPData.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
	Logger logger = LoggerFactory.getLogger(GetSomeAFPData.class);

	Proxy proxy = null;
	// If you are behind a proxy, use the following line with the correct parameters :
	// proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("firewall.company.com", 80));

	Map<String, String> authentication = null;
	// If you want to use your credentials on api.afp.com, provide the following informations :
	// authentication = new HashMap<String, String>();
	// authentication.put(AFPAuthenticationManager.KEY_CLIENT, "client");
	// authentication.put(AFPAuthenticationManager.KEY_SECRET, "secret");
	// authentication.put(AFPAuthenticationManager.KEY_USERNAME, "username");
	// authentication.put(AFPAuthenticationManager.KEY_PASSWORD, "password");

	AFPDataGrabber afp = new AFPDataGrabber(LangEnum.EN, authentication, logger, dataDir,
			AFPDataGrabberCache.noCache(), proxy);

	AFPGrabSession gs = afp.grabSearchMax(false, 10);
	logger.info("Grabbed " + gs.getAllDocuments().size() + " documents as [" + gs.getAuthenticatedAs() + "] in "
			+ gs.getDir());
	for (FullNewsDocument nd : gs.getAllDocuments()) {
		logger.info("    - " + nd.getUno() + " : " + nd.getFullTitle());
	}
}
 
Example 7
Project: educational-plugin   File: EduStepicClient.java   View source code 6 votes vote down vote up
@NotNull
static HttpClientBuilder getBuilder() {
  final HttpClientBuilder builder = HttpClients.custom().setSSLContext(CertificateManager.getInstance().getSslContext()).
    setMaxConnPerRoute(100000).setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE);

  final HttpConfigurable proxyConfigurable = HttpConfigurable.getInstance();
  final List<Proxy> proxies = proxyConfigurable.getOnlyBySettingsSelector().select(URI.create(EduStepicNames.STEPIC_URL));
  final InetSocketAddress address = proxies.size() > 0 ? (InetSocketAddress)proxies.get(0).address() : null;
  if (address != null) {
    builder.setProxy(new HttpHost(address.getHostName(), address.getPort()));
  }
  final ConfirmingTrustManager trustManager = CertificateManager.getInstance().getTrustManager();
  try {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[]{trustManager}, new SecureRandom());
    builder.setSSLContext(sslContext);
  }
  catch (NoSuchAlgorithmException | KeyManagementException e) {
    LOG.error(e.getMessage());
  }
  return builder;
}
 
Example 8
Project: FirefoxData-android   File: SystemDefaultRoutePlanner.java   View source code 6 votes vote down vote up
private Proxy chooseProxy(final List<Proxy> proxies) {
    Proxy result = null;
    // check the list for one we can use
    for (int i=0; (result == null) && (i < proxies.size()); i++) {
        final Proxy p = proxies.get(i);
        switch (p.type()) {

        case DIRECT:
        case HTTP:
            result = p;
            break;

        case SOCKS:
            // SOCKS hosts are not handled on the route level.
            // The socket may make use of the SOCKS host though.
            break;
        }
    }
    if (result == null) {
        //@@@ log as warning or info that only a socks proxy is available?
        // result can only be null if all proxies are socks proxies
        // socks proxies are not handled on the route planning level
        result = Proxy.NO_PROXY;
    }
    return result;
}
 
Example 9
Project: jdk8u-jdk   File: SocksConnectTimeout.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 10
Project: BaseClient   File: HttpPipelineConnection.java   View source code 6 votes vote down vote up
public HttpPipelineConnection(String p_i48_1_, int p_i48_2_, Proxy p_i48_3_)
{
    this.host = null;
    this.port = 0;
    this.proxy = Proxy.NO_PROXY;
    this.listRequests = new LinkedList();
    this.listRequestsSend = new LinkedList();
    this.socket = null;
    this.inputStream = null;
    this.outputStream = null;
    this.httpPipelineSender = null;
    this.httpPipelineReceiver = null;
    this.countRequests = 0;
    this.responseReceived = false;
    this.keepaliveTimeoutMs = 5000L;
    this.keepaliveMaxCount = 1000;
    this.timeLastActivityMs = System.currentTimeMillis();
    this.terminated = false;
    this.host = p_i48_1_;
    this.port = p_i48_2_;
    this.proxy = p_i48_3_;
    this.httpPipelineSender = new HttpPipelineSender(this);
    this.httpPipelineSender.start();
    this.httpPipelineReceiver = new HttpPipelineReceiver(this);
    this.httpPipelineReceiver.start();
}
 
Example 11
Project: chromium-net-for-android   File: AndroidProxySelectorTest.java   View source code 6 votes vote down vote up
static String toString(Proxy proxy) {
    if (proxy == Proxy.NO_PROXY)
        return "DIRECT";
    // java.net.Proxy only knows about http and socks proxies.
    Proxy.Type type = proxy.type();
    switch (type) {
        case HTTP:
            return "PROXY " + proxy.address().toString();
        case SOCKS:
            return "SOCKS5 " + proxy.address().toString();
        case DIRECT:
            return "DIRECT";
        default:
            // If a new proxy type is supported in future, add a case to match it.
            fail("Unknown proxy type" + type);
            return "unknown://";
    }
}
 
Example 12
Project: afp-api-client   File: AFPDataGrabber.java   View source code 6 votes vote down vote up
public AFPDataGrabber(LangEnum lang, Map<String, String> authenticationProperties, Logger logger, File baseDir,
		AFPDataGrabberCache cache, Proxy proxy) {
	super();
	aam = new AFPAuthenticationManager(authenticationProperties, proxy, logger);
	this.logger = logger;
	this.baseDir = baseDir;
	this.proxy = proxy;
	this.cache = cache;
	lng = lang;
	directoryDF = new SimpleDateFormat("yyyy/MM/dd/", Locale.FRANCE);
	directoryDF.setTimeZone(TimeZone.getTimeZone("Europe/Paris"));
	fileDF = new SimpleDateFormat("HHmmssSSS", Locale.FRANCE);
	fileDF.setTimeZone(TimeZone.getTimeZone("Europe/Paris"));
	dateDF = new SimpleDateFormat("yyyyMMdd", Locale.FRANCE);
	dateDF.setTimeZone(TimeZone.getTimeZone("Europe/Paris"));
}
 
Example 13
Project: LoRaWAN-Smart-Parking   File: HttpAuthenticator.java   View source code 6 votes vote down vote up
@Override public Credential authenticateProxy(
    Proxy proxy, URL url, List<Challenge> challenges) throws IOException {
  for (Challenge challenge : challenges) {
    if (!"Basic".equalsIgnoreCase(challenge.getScheme())) {
      continue;
    }

    InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
    PasswordAuthentication auth = Authenticator.requestPasswordAuthentication(
        proxyAddress.getHostName(), getConnectToInetAddress(proxy, url), proxyAddress.getPort(),
        url.getProtocol(), challenge.getRealm(), challenge.getScheme(), url,
        Authenticator.RequestorType.PROXY);
    if (auth != null) {
      return Credential.basic(auth.getUserName(), new String(auth.getPassword()));
    }
  }
  return null;
}
 
Example 14
Project: probe   File: HttpProxyClient.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    final String user = "probe";
    final String password = "probe";

    Proxy proxyTest = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 10779));

    java.net.Authenticator.setDefault(new java.net.Authenticator() {
        private PasswordAuthentication authentication = new PasswordAuthentication(user, password.toCharArray());

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return authentication;
        }
    });

    OkHttpClient client = new OkHttpClient.Builder().proxy(proxyTest).build();
    Request request = new Request.Builder().url("https://www.baidu.com").build();
    Response response = client.newCall(request).execute();
    System.out.println("状态码: " + response.code());
    System.out.println("响应内容: \n" + response.body().string());

    client.dispatcher().executorService().shutdown();
    client.connectionPool().evictAll();
}
 
Example 15
Project: incubator-netbeans   File: MyProxySelector.java   View source code 6 votes vote down vote up
public List<Proxy> select(URI uri) {
    if (uri == null) {
        throw new IllegalArgumentException(ResourceUtils.getString(
                MyProxySelector.class, 
                ERROR_URI_CANNOT_BE_NULL_KEY));
    }
    Proxy proxy = Proxy.NO_PROXY;
    if (byPassSet.contains(uri.getHost())) {
        return Collections.singletonList(proxy);
    }
    if (HTTP_SCHEME.equalsIgnoreCase(uri.getScheme()) || 
            HTTPS_SCHEME.equalsIgnoreCase(uri.getScheme())) {
        if (proxies.containsKey(MyProxyType.HTTP)) {
            proxy = proxies.get(MyProxyType.HTTP).getProxy();
        }
    } else if (FTP_SCHEME.equalsIgnoreCase(uri.getScheme())) {
        if (proxies.containsKey(MyProxyType.FTP)) {
            proxy = proxies.get(MyProxyType.FTP).getProxy();
        }
    } else {
        if (proxies.containsKey(MyProxyType.SOCKS)) {
            proxy = proxies.get(MyProxyType.SOCKS).getProxy();
        }
    }
    return Collections.singletonList(proxy);
}
 
Example 16
Project: incubator-netbeans   File: ProxyTest.java   View source code 6 votes vote down vote up
public void testProxySerializing() {
    final MyProxy proxy = new MyProxy(
        new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 4321)));
    final MyProxy desirealized = new MyProxy();
    try {
        Document doc = DomUtil.parseXmlFile("<proxy-test/>");
        DomUtil.addChild(doc.getDocumentElement(), proxy);
        
        DomVisitor visitor = new RecursiveDomVisitor() {
            public void visit(Element element) {
                if ("proxy".equals(element.getNodeName())) {
                    desirealized.readXML(element);
                } else super.visit(element);
            }
        };
        visitor.visit(doc);
    } catch(ParseException ex) {}
    assertEquals(proxy, desirealized);
}
 
Example 17
Project: GitHub   File: Route.java   View source code 5 votes vote down vote up
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;
}
 
Example 18
Project: yadaframework   File: YadaHttpUtil.java   View source code 5 votes vote down vote up
/**
	 * Validate a proxy over a given http page
	 * @param proxyAddress
	 * @param proxyPort
	 * @param testUrl the page to fetch (must include the third slash if just the host, like "http://somehost.com/"
	 * @param timeoutMillis
	 * @param username proxy basic authentication, or null when not needed
	 * @param password proxy basic authentication, or null when not needed
	 * @param userAgent to use when connecting (can be null for the default). E.g. "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0"
	 * @return the milliseconds taken to fetch the page, or -1 in case of error/timeout
	 */
	public long validateProxy(String proxyAddress, int proxyPort, URL testUrl, int timeoutMillis, String username, String password, String userAgent) {
		long start = System.currentTimeMillis();
		Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, proxyPort));
		try {
			URLConnection connection = testUrl.openConnection(proxy);
			connection.setReadTimeout(timeoutMillis);
			connection.setConnectTimeout(timeoutMillis);
			connection.setUseCaches(false);
			connection.getRequestProperty(password);
			if (userAgent!=null) {
				connection.setRequestProperty("User-Agent", userAgent);
			}
			if (username!=null && password !=null) {
				String auth = "Basic " + Base64Utils.encodeToString((username + ":" + password).getBytes());
				connection.setRequestProperty("Proxy-Connection", "Keep-Alive");
				connection.setRequestProperty("Proxy-Authorization", auth);
			}
			connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
			connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String inputLine = null;
			while ((inputLine = in.readLine()) != null); 
			in.close();
			return System.currentTimeMillis()-start;
		} catch (IOException e) {
			log.debug("Failed to validate proxy {}", proxyAddress, e);
		}
		return -1;
//		Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.10.100.100", 80));
//		HttpURLConnection connection =(HttpURLConnection)new URL("http://abc.abcd.com").openConnection(proxy);
//		connection.setDoOutput(true);
//		connection.setDoInput(true);
//		connection.setRequestProperty("Content-type", "text/xml");
//		connection.setRequestProperty("Accept", "text/xml, application/xml");
//		connection.setRequestMethod("POST");
	}
 
Example 19
Project: GitHub   File: RequestLine.java   View source code 5 votes vote down vote up
/**
 * Returns the request status line, like "GET / HTTP/1.1". This is exposed to the application by
 * {@link HttpURLConnection#getHeaderFields}, so it needs to be set even if the transport is
 * HTTP/2.
 */
public static String get(Request request, Proxy.Type proxyType) {
  StringBuilder result = new StringBuilder();
  result.append(request.method());
  result.append(' ');

  if (includeAuthorityInRequestLine(request, proxyType)) {
    result.append(request.url());
  } else {
    result.append(requestPath(request.url()));
  }

  result.append(" HTTP/1.1");
  return result.toString();
}
 
Example 20
Project: hadoop   File: TestJobEndNotifier.java   View source code 5 votes vote down vote up
private void testProxyConfiguration(Configuration conf) {
  conf.set(MRJobConfig.MR_JOB_END_NOTIFICATION_PROXY, "somehost");
  setConf(conf);
  Assert.assertTrue("Proxy shouldn't be set because port wasn't specified",
    proxyToUse.type() == Proxy.Type.DIRECT);
  conf.set(MRJobConfig.MR_JOB_END_NOTIFICATION_PROXY, "somehost:someport");
  setConf(conf);
  Assert.assertTrue("Proxy shouldn't be set because port wasn't numeric",
    proxyToUse.type() == Proxy.Type.DIRECT);
  conf.set(MRJobConfig.MR_JOB_END_NOTIFICATION_PROXY, "somehost:1000");
  setConf(conf);
  Assert.assertTrue("Proxy should have been set but wasn't ",
    proxyToUse.toString().equals("HTTP @ somehost:1000"));
  conf.set(MRJobConfig.MR_JOB_END_NOTIFICATION_PROXY, "[email protected]:1000");
  setConf(conf);
  Assert.assertTrue("Proxy should have been socks but wasn't ",
    proxyToUse.toString().equals("SOCKS @ somehost:1000"));
  conf.set(MRJobConfig.MR_JOB_END_NOTIFICATION_PROXY, "[email protected]:1000");
  setConf(conf);
  Assert.assertTrue("Proxy should have been socks but wasn't ",
    proxyToUse.toString().equals("SOCKS @ somehost:1000"));
  conf.set(MRJobConfig.MR_JOB_END_NOTIFICATION_PROXY, "[email protected]:1000");
  setConf(conf);
  Assert.assertTrue("Proxy should have been http but wasn't ",
    proxyToUse.toString().equals("HTTP @ somehost:1000"));
  
}
 
Example 21
Project: dlface   File: Util.java   View source code 5 votes vote down vote up
/**
 * TODO: make this public, global used with callbacks ... (maybe some factory/builder)
 */
private static void downloadUsingProxy(URL source, File destination, Proxy proxy) throws IOException {
    try(OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(destination));
        InputStream inputStream = source.openConnection(proxy).getInputStream()) {

        byte[] buffer = new byte[DOWNLOAD_BUFFER];
        int len;
        while ((len = inputStream.read(buffer)) >= 0) {
            outputStream.write(buffer, 0, len);
        }
    }
}
 
Example 22
Project: GitHub   File: RouteSelector.java   View source code 5 votes vote down vote up
/** Prepares the proxy servers to try. */
private void resetNextProxy(HttpUrl url, Proxy proxy) {
  if (proxy != null) {
    // If the user specifies a proxy, try that and only that.
    proxies = Collections.singletonList(proxy);
  } else {
    // Try each of the ProxySelector choices until one connection succeeds.
    List<Proxy> proxiesOrNull = address.proxySelector().select(url.uri());
    proxies = proxiesOrNull != null && !proxiesOrNull.isEmpty()
        ? Util.immutableList(proxiesOrNull)
        : Util.immutableList(Proxy.NO_PROXY);
  }
  nextProxyIndex = 0;
}
 
Example 23
Project: openjdk-jdk10   File: HttpNegotiateServer.java   View source code 5 votes vote down vote up
static void test6829283() throws Exception {
    BufferedReader reader;
    java.net.Authenticator.setDefault(new KnowNothingAuthenticator());
    try {
        new BufferedReader(new InputStreamReader(
                webUrl.openConnection(Proxy.NO_PROXY).getInputStream()));
    } catch (IOException ioe) {
        // Will fail since no username and password is provided.
    }
    if (count > 1) {
        throw new RuntimeException("Authenticator called twice");
    }
}
 
Example 24
Project: socks5-netty   File: HttpProxyClient.java   View source code 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	final String user = "test";
	final String password = "test";
	
	Proxy proxyTest = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 11080));
	
	java.net.Authenticator.setDefault(new java.net.Authenticator()
	{
		private PasswordAuthentication authentication = new PasswordAuthentication(user, password.toCharArray());

		@Override
		protected PasswordAuthentication getPasswordAuthentication()
		{
			return authentication;
		}
	});

	
	OkHttpClient client = new OkHttpClient.Builder().proxy(proxyTest).build();
	Request request = new Request.Builder().url("https://www.baidu.com").build();
	Response response = client.newCall(request).execute();
	System.out.println(response.code());
	System.out.println(response.body().string());
	
	client.dispatcher().executorService().shutdown();
	client.connectionPool().evictAll();
}
 
Example 25
Project: slacklet   File: SlackWebSocketSessionImpl.java   View source code 5 votes vote down vote up
SlackWebSocketSessionImpl(WebSocketContainerProvider webSocketContainerProvider, String authToken, Proxy.Type proxyType, String proxyAddress, int proxyPort, boolean reconnectOnDisconnection, long heartbeat, TimeUnit unit) {
    this.authToken = authToken;
    this.proxyAddress = proxyAddress;
    this.proxyPort = proxyPort;
    this.proxyHost = new HttpHost(proxyAddress, proxyPort);
    this.reconnectOnDisconnection = reconnectOnDisconnection;
    this.heartbeat = heartbeat != 0 ? unit.toMillis(heartbeat) : DEFAULT_HEARTBEAT_IN_MILLIS;
    this.webSocketContainerProvider = webSocketContainerProvider != null ? webSocketContainerProvider : new DefaultWebSocketContainerProvider(proxyAddress,proxyPort);
    addInternalListeners();
}
 
Example 26
Project: Cybernet-VPN   File: ProxyDetection.java   View source code 5 votes vote down vote up
static Proxy getFirstProxy(URL url) throws URISyntaxException {
    System.setProperty("java.net.useSystemProxies", "true");
    List<Proxy> proxylist = ProxySelector.getDefault().select(url.toURI());
    if (proxylist != null) {
        for (Proxy proxy : proxylist) {
            SocketAddress addr = proxy.address();
            if (addr != null) {
                return proxy;
            }
        }
    }
    return null;
}
 
Example 27
Project: oscm   File: OpenStackConnectionTest.java   View source code 5 votes vote down vote up
@Test
public void processRequest_IOException() {
    // given
    final String msg = "get out of my way!";
    OpenStackConnection.setURLStreamHandler(new MockURLStreamHandler() {
        @Override
        protected URLConnection openConnection(URL u, Proxy p)
                throws IOException {
            return new HttpURLConnection(u, (Proxy) null) {
                @Override
                public void connect() throws IOException {
                    throw new IOException(msg);
                }
            };
        }
    });

    // when
    try {
        givenOpenStackConnetion().processRequest(
                "http://openservicecatalogmanager.org", "POST");
        assertTrue("Test must fail with HeatException!", false);
    } catch (OpenStackConnectionException ex) {
        // then
        assertTrue(ex.getMessage().indexOf("send failed") > -1);
        assertTrue(ex.getMessage().indexOf(msg) > -1);
    }
}
 
Example 28
Project: BiglyBT   File: Handler.java   View source code 5 votes vote down vote up
@Override
public URLConnection
openConnection(
	URL 		u,
	Proxy		proxy )

	throws IOException
{
	throw( new IOException( "chat: URIs can't be used directly" ));
}
 
Example 29
Project: BaseClient   File: HttpRequest.java   View source code 5 votes vote down vote up
public HttpRequest(String p_i52_1_, int p_i52_2_, Proxy p_i52_3_, String p_i52_4_, String p_i52_5_, String p_i52_6_, Map<String, String> p_i52_7_, byte[] p_i52_8_)
{
    this.host = p_i52_1_;
    this.port = p_i52_2_;
    this.proxy = p_i52_3_;
    this.method = p_i52_4_;
    this.file = p_i52_5_;
    this.http = p_i52_6_;
    this.headers = p_i52_7_;
    this.body = p_i52_8_;
}
 
Example 30
Project: hadoop   File: SocksSocketFactory.java   View source code 5 votes vote down vote up
/**
 * Set the proxy of this socket factory as described in the string
 * parameter
 * 
 * @param proxyStr the proxy address using the format "host:port"
 */
private void setProxy(String proxyStr) {
  String[] strs = proxyStr.split(":", 2);
  if (strs.length != 2)
    throw new RuntimeException("Bad SOCKS proxy parameter: " + proxyStr);
  String host = strs[0];
  int port = Integer.parseInt(strs[1]);
  this.proxy =
      new Proxy(Proxy.Type.SOCKS, InetSocketAddress.createUnresolved(host,
          port));
}
 
Example 31
Project: BaseClient   File: HttpPipeline.java   View source code 5 votes vote down vote up
private static synchronized HttpPipelineConnection getConnection(String p_getConnection_0_, int p_getConnection_1_, Proxy p_getConnection_2_)
{
    String s = makeConnectionKey(p_getConnection_0_, p_getConnection_1_, p_getConnection_2_);
    HttpPipelineConnection httppipelineconnection = (HttpPipelineConnection)mapConnections.get(s);

    if (httppipelineconnection == null)
    {
        httppipelineconnection = new HttpPipelineConnection(p_getConnection_0_, p_getConnection_1_, p_getConnection_2_);
        mapConnections.put(s, httppipelineconnection);
    }

    return httppipelineconnection;
}
 
Example 32
Project: redisfx   File: JedisManager.java   View source code 5 votes vote down vote up
/**
 * create a JedisPool instance.
 *
 * @param host      Redis server host
 * @param port      Redis server port
 * @param passphase (nullable) Redis server passphase
 * @param proxy     (nullable) proxy
 *
 * @return a JedisPool instance
 */
public static JedisPool createJedisPool(
        String host, Integer port, String passphase, Proxy proxy) {

    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();

    if (!StringUtils.isBlank(passphase)) {
        return new JedisPool(poolConfig, host, port, DEFAULT_TIMEOUT, passphase, proxy);
    } else {
        return new JedisPool(poolConfig, host, port, DEFAULT_TIMEOUT, proxy);
    }
}
 
Example 33
Project: GitHub   File: RealConnection.java   View source code 5 votes vote down vote up
/** Does all the work necessary to build a full HTTP or HTTPS connection on a raw socket. */
private void connectSocket(int connectTimeout, int readTimeout, Call call,
    EventListener eventListener) throws IOException {
  Proxy proxy = route.proxy();
  Address address = route.address();

  rawSocket = proxy.type() == Proxy.Type.DIRECT || proxy.type() == Proxy.Type.HTTP
      ? address.socketFactory().createSocket()
      : new Socket(proxy);

  eventListener.connectStart(call, route.socketAddress(), proxy);
  rawSocket.setSoTimeout(readTimeout);
  try {
    Platform.get().connectSocket(rawSocket, route.socketAddress(), connectTimeout);
  } catch (ConnectException e) {
    ConnectException ce = new ConnectException("Failed to connect to " + route.socketAddress());
    ce.initCause(e);
    throw ce;
  }

  // The following try/catch block is a pseudo hacky way to get around a crash on Android 7.0
  // More details:
  // https://github.com/square/okhttp/issues/3245
  // https://android-review.googlesource.com/#/c/271775/
  try {
    source = Okio.buffer(Okio.source(rawSocket));
    sink = Okio.buffer(Okio.sink(rawSocket));
  } catch (NullPointerException npe) {
    if (NPE_THROW_WITH_NULL.equals(npe.getMessage())) {
      throw new IOException(npe);
    }
  }
}
 
Example 34
Project: GitHub   File: RouteSelector.java   View source code 5 votes vote down vote up
public Selection next() throws IOException {
  if (!hasNext()) {
    throw new NoSuchElementException();
  }

  // Compute the next set of routes to attempt.
  List<Route> routes = new ArrayList<>();
  while (hasNextProxy()) {
    // Postponed routes are always tried last. For example, if we have 2 proxies and all the
    // routes for proxy1 should be postponed, we'll move to proxy2. Only after we've exhausted
    // all the good routes will we attempt the postponed routes.
    Proxy proxy = nextProxy();
    for (int i = 0, size = inetSocketAddresses.size(); i < size; i++) {
      Route route = new Route(address, proxy, inetSocketAddresses.get(i));
      if (routeDatabase.shouldPostpone(route)) {
        postponedRoutes.add(route);
      } else {
        routes.add(route);
      }
    }

    if (!routes.isEmpty()) {
      break;
    }
  }

  if (routes.isEmpty()) {
    // We've exhausted all Proxies so fallback to the postponed routes.
    routes.addAll(postponedRoutes);
    postponedRoutes.clear();
  }

  return new Selection(routes);
}
 
Example 35
Project: GitHub   File: RouteSelector.java   View source code 5 votes vote down vote up
/** Prepares the proxy servers to try. */
private void resetNextProxy(HttpUrl url, Proxy proxy) {
  if (proxy != null) {
    // If the user specifies a proxy, try that and only that.
    proxies = Collections.singletonList(proxy);
  } else {
    // Try each of the ProxySelector choices until one connection succeeds.
    List<Proxy> proxiesOrNull = address.proxySelector().select(url.uri());
    proxies = proxiesOrNull != null && !proxiesOrNull.isEmpty()
        ? Util.immutableList(proxiesOrNull)
        : Util.immutableList(Proxy.NO_PROXY);
  }
  nextProxyIndex = 0;
}
 
Example 36
Project: jdk8u-jdk   File: BadProxySelector.java   View source code 5 votes vote down vote up
@Override
public List<Proxy> select(URI uri) {
    List<Proxy> proxies = new ArrayList<>();
    proxies.add(new Proxy(Proxy.Type.HTTP,
                          new InetSocketAddress("localhost", 0)));
    proxies.add(new Proxy(Proxy.Type.HTTP,
                          new InetSocketAddress("localhost", 0)));
    return proxies;
}
 
Example 37
Project: nifi-android-s2s   File: HttpPeerConnector.java   View source code 5 votes vote down vote up
private Proxy getProxy(SiteToSiteRemoteCluster siteToSiteRemoteCluster) {
    String proxyHost = siteToSiteRemoteCluster.getProxyHost();
    if (proxyHost == null || proxyHost.isEmpty()) {
        return null;
    }

    int proxyPort = siteToSiteRemoteCluster.getProxyPort();
    int port = 80;
    if (proxyPort <= 65535 && proxyPort > 0) {
        port = proxyPort;
    }
    return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, port));
}
 
Example 38
Project: DecompiledMinecraft   File: MinecraftServer.java   View source code 5 votes vote down vote up
public MinecraftServer(File workDir, Proxy proxy, File profileCacheDir)
{
    this.serverProxy = proxy;
    mcServer = this;
    this.anvilFile = workDir;
    this.networkSystem = new NetworkSystem(this);
    this.profileCache = new PlayerProfileCache(this, profileCacheDir);
    this.commandManager = this.createNewCommandManager();
    this.anvilConverterForAnvilFile = new AnvilSaveConverter(workDir);
    this.authService = new YggdrasilAuthenticationService(proxy, UUID.randomUUID().toString());
    this.sessionService = this.authService.createMinecraftSessionService();
    this.profileRepo = this.authService.createProfileRepository();
}
 
Example 39
Project: openjdk-jdk10   File: ProxyTest2.java   View source code 5 votes vote down vote up
public static void test(Http2TestServer server, HttpClient.Version version)
        throws Exception
{
    System.out.println("Server is: " + server.getAddress().toString());
    URI uri = new URI("https://localhost:" + server.getAddress().getPort() + PATH + "x");
    TunnelingProxy proxy = new TunnelingProxy(server);
    proxy.start();
    try {
        System.out.println("Proxy started");
        Proxy p = new Proxy(Proxy.Type.HTTP,
                InetSocketAddress.createUnresolved("localhost", proxy.getAddress().getPort()));
        System.out.println("Setting up request with HttpClient for version: "
                + version.name() + "URI=" + uri);
        ProxySelector ps = ProxySelector.of(
                InetSocketAddress.createUnresolved("localhost", proxy.getAddress().getPort()));
        HttpClient client = HttpClient.newBuilder()
            .version(version)
            .proxy(ps)
            .build();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(uri)
            .GET()
            .build();

        System.out.println("Sending request with HttpClient");
        HttpResponse<String> response
            = client.send(request, HttpResponse.BodyHandler.asString());
        System.out.println("Got response");
        String resp = response.body();
        System.out.println("Received: " + resp);
        if (!RESPONSE.equals(resp)) {
            throw new AssertionError("Unexpected response");
        }
    } finally {
        System.out.println("Stopping proxy");
        proxy.stop();
        System.out.println("Proxy stopped");
    }
}
 
Example 40
Project: Lantern-sdk   File: LanternHttpURLConnection.java   View source code 5 votes vote down vote up
public LanternHttpURLConnection (URL url, Proxy proxy) {
    super (url);
    requestProperties = new Hashtable();
    keys = new Vector();
    headers = new Hashtable();
    this.proxy = proxy;
}