本文整理匯總了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);
}
示例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;
}
示例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));
}
示例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;
}
示例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()));
}
示例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());
}
}
示例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;
}
示例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;
}
示例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);
}
}
示例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();
}
示例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://";
}
}
示例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"));
}
示例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;
}
示例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();
}
示例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);
}