Java 类java.net.Proxy 实例源码

项目:GitHub    文件:Address.java   
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;
}
项目:owa-notifier    文件:RestfullAcessProxy.java   
/**
 * 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);
}
项目:GitHub    文件:RealConnection.java   
/** 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));
}
项目:Backmemed    文件:Manager.java   
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;
}
项目:Proyecto-DASI    文件:GradleStart.java   
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()));
}
项目:afp-api-client    文件:GetSomeAFPData.java   
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());
    }
}
项目:educational-plugin    文件:EduStepicClient.java   
@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;
}
项目:FirefoxData-android    文件:SystemDefaultRoutePlanner.java   
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;
}
项目:jdk8u-jdk    文件:SocksConnectTimeout.java   
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);
    }
}
项目:BaseClient    文件:HttpPipelineConnection.java   
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();
}
项目:chromium-net-for-android    文件:AndroidProxySelectorTest.java   
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://";
    }
}
项目:afp-api-client    文件:AFPDataGrabber.java   
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"));
}
项目:LoRaWAN-Smart-Parking    文件:HttpAuthenticator.java   
@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;
}
项目:probe    文件:HttpProxyClient.java   
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();
}
项目:incubator-netbeans    文件:MyProxySelector.java   
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);
}
项目:incubator-netbeans    文件:ProxyTest.java   
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);
}
项目:GitHub    文件:Route.java   
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;
}
项目:yadaframework    文件:YadaHttpUtil.java   
/**
     * 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");
    }
项目:GitHub    文件:RequestLine.java   
/**
 * 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();
}
项目:dlface    文件:Util.java   
/**
 * 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);
        }
    }
}
项目:GitHub    文件:RouteSelector.java   
/** 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;
}
项目:openjdk-jdk10    文件:HttpNegotiateServer.java   
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");
    }
}
项目:socks5-netty    文件:HttpProxyClient.java   
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();
}
项目:slacklet    文件:SlackWebSocketSessionImpl.java   
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();
}
项目:Cybernet-VPN    文件:ProxyDetection.java   
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;
}
项目:oscm    文件:OpenStackConnectionTest.java   
@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);
    }
}
项目:BiglyBT    文件:Handler.java   
@Override
public URLConnection
openConnection(
    URL         u,
    Proxy       proxy )

    throws IOException
{
    throw( new IOException( "chat: URIs can't be used directly" ));
}
项目:BaseClient    文件:HttpRequest.java   
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_;
}
项目:hadoop    文件:SocksSocketFactory.java   
/**
 * 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));
}
项目:BaseClient    文件:HttpPipeline.java   
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;
}
项目:redisfx    文件:JedisManager.java   
/**
 * 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);
    }
}
项目:GitHub    文件:RealConnection.java   
/** 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);
    }
  }
}
项目:GitHub    文件:RouteSelector.java   
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);
}
项目:GitHub    文件:RouteSelector.java   
/** 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;
}
项目:jdk8u-jdk    文件:BadProxySelector.java   
@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;
}
项目:nifi-android-s2s    文件:HttpPeerConnector.java   
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));
}
项目:DecompiledMinecraft    文件:MinecraftServer.java   
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();
}
项目:openjdk-jdk10    文件:ProxyTest2.java   
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");
    }
}
项目:Lantern-sdk    文件:LanternHttpURLConnection.java   
public LanternHttpURLConnection (URL url, Proxy proxy) {
    super (url);
    requestProperties = new Hashtable();
    keys = new Vector();
    headers = new Hashtable();
    this.proxy = proxy;
}