當前位置: 首頁>>代碼示例>>Java>>正文


Java Proxy類代碼示例

本文整理匯總了Java中java.net.Proxy的典型用法代碼示例。如果您正苦於以下問題:Java Proxy類的具體用法?Java Proxy怎麽用?Java Proxy使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Proxy類屬於java.net包,在下文中一共展示了Proxy類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getRealTokenService

import java.net.Proxy; //導入依賴的package包/類
/**
 * 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);
}
 
開發者ID:OwaNotifier,項目名稱:owa-notifier,代碼行數:28,代碼來源:RestfullAcessProxy.java

示例2: Address

import java.net.Proxy; //導入依賴的package包/類
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;
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:37,代碼來源:Address.java

示例3: connectSocket

import java.net.Proxy; //導入依賴的package包/類
/** 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));
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:21,代碼來源:RealConnection.java

示例4: loginPassword

import java.net.Proxy; //導入依賴的package包/類
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;
}
 
開發者ID:sudofox,項目名稱:Backmemed,代碼行數:21,代碼來源:Manager.java

示例5: attemptLogin

import java.net.Proxy; //導入依賴的package包/類
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()));
}
 
開發者ID:Yarichi,項目名稱:Proyecto-DASI,代碼行數:27,代碼來源:GradleStart.java

示例6: main

import java.net.Proxy; //導入依賴的package包/類
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());
	}
}
 
開發者ID:ina-foss,項目名稱:afp-api-client,代碼行數:26,代碼來源:GetSomeAFPData.java

示例7: getBuilder

import java.net.Proxy; //導入依賴的package包/類
@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;
}
 
開發者ID:medvector,項目名稱:educational-plugin,代碼行數:23,代碼來源:EduStepicClient.java

示例8: chooseProxy

import java.net.Proxy; //導入依賴的package包/類
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;
}
 
開發者ID:mozilla-mobile,項目名稱:FirefoxData-android,代碼行數:27,代碼來源:SystemDefaultRoutePlanner.java

示例9: main

import java.net.Proxy; //導入依賴的package包/類
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);
    }
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:23,代碼來源:SocksConnectTimeout.java

示例10: HttpPipelineConnection

import java.net.Proxy; //導入依賴的package包/類
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();
}
 
開發者ID:SkidJava,項目名稱:BaseClient,代碼行數:27,代碼來源:HttpPipelineConnection.java

示例11: toString

import java.net.Proxy; //導入依賴的package包/類
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://";
    }
}
 
開發者ID:lizhangqu,項目名稱:chromium-net-for-android,代碼行數:19,代碼來源:AndroidProxySelectorTest.java

示例12: AFPDataGrabber

import java.net.Proxy; //導入依賴的package包/類
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"));
}
 
開發者ID:ina-foss,項目名稱:afp-api-client,代碼行數:17,代碼來源:AFPDataGrabber.java

示例13: authenticateProxy

import java.net.Proxy; //導入依賴的package包/類
@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;
}
 
開發者ID:aabognah,項目名稱:LoRaWAN-Smart-Parking,代碼行數:19,代碼來源:HttpAuthenticator.java

示例14: main

import java.net.Proxy; //導入依賴的package包/類
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();
}
 
開發者ID:biezhi,項目名稱:probe,代碼行數:25,代碼來源:HttpProxyClient.java

示例15: select

import java.net.Proxy; //導入依賴的package包/類
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);
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:27,代碼來源:MyProxySelector.java


注:本文中的java.net.Proxy類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。