下面列出了怎么用java.net.Proxy.Type的API类实例代码及写法,或者点击链接到github查看源代码。
public static void initHttpProxy(OkHttpClient.Builder builder, String proxyHostAddress, int proxyPort,
final String proxyUser, final String proxyPassword, String proxyDomain, String proxyWorkstation) {
if (proxyHostAddress != null && proxyPort != -1) {
if (log.isInfoEnabled()) {
log.info("Using Proxy: " + proxyHostAddress + ":" + proxyPort);
}
builder.proxy(new java.net.Proxy(Type.HTTP, new InetSocketAddress(proxyHostAddress, proxyPort)));
if (proxyUser != null && !proxyUser.trim().equals("")) {
Authenticator proxyAuthenticator = new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic(proxyUser, proxyPassword);
return response.request().newBuilder().header(CommonHeaders.PROXY_AUTHORIZATION, credential)
.build();
}
};
builder.proxyAuthenticator(proxyAuthenticator);
}
}
}
private static HttpURLConnection a(Context context, String str) {
try {
URL url = new URL(str);
if (context.getPackageManager().checkPermission(z[43], context.getPackageName()) == 0) {
NetworkInfo activeNetworkInfo = ((ConnectivityManager) context.getSystemService(z[44])).getActiveNetworkInfo();
if (!(activeNetworkInfo == null || activeNetworkInfo.getType() == 1)) {
String extraInfo = activeNetworkInfo.getExtraInfo();
if (extraInfo != null && (extraInfo.equals(z[40]) || extraInfo.equals(z[41]) || extraInfo.equals(z[42]))) {
return (HttpURLConnection) url.openConnection(new Proxy(Type.HTTP, new InetSocketAddress(z[45], 80)));
}
}
}
return (HttpURLConnection) url.openConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e2) {
e2.printStackTrace();
return null;
}
}
private Proxy getProxy(URI uri) {
if (proxyService == null) {
return Proxy.NO_PROXY;
}
IProxyData[] proxies = proxyService.select(uri);
for (IProxyData proxyData : proxies) {
switch (proxyData.getType()) {
case IProxyData.HTTPS_PROXY_TYPE:
case IProxyData.HTTP_PROXY_TYPE:
return new Proxy(
Type.HTTP, new InetSocketAddress(proxyData.getHost(), proxyData.getPort()));
case IProxyData.SOCKS_PROXY_TYPE:
return new Proxy(
Type.SOCKS, new InetSocketAddress(proxyData.getHost(), proxyData.getPort()));
default:
logger.warning("Unknown proxy-data type: " + proxyData.getType()); //$NON-NLS-1$
break;
}
}
return Proxy.NO_PROXY;
}
@VisibleForTesting
public Proxy createProxy(URI uri) {
Preconditions.checkNotNull(uri, "uri is null");
Preconditions.checkArgument(!"http".equals(uri.getScheme()), "http is not a supported schema");
IProxyService proxyServiceCopy = proxyService;
if (proxyServiceCopy == null) {
return Proxy.NO_PROXY;
}
IProxyData[] proxyDataForUri = proxyServiceCopy.select(uri);
for (final IProxyData iProxyData : proxyDataForUri) {
switch (iProxyData.getType()) {
case IProxyData.HTTPS_PROXY_TYPE:
return new Proxy(Type.HTTP, new InetSocketAddress(iProxyData.getHost(),
iProxyData.getPort()));
case IProxyData.SOCKS_PROXY_TYPE:
return new Proxy(Type.SOCKS, new InetSocketAddress(iProxyData.getHost(),
iProxyData.getPort()));
default:
logger.warning("Unsupported proxy type: " + iProxyData.getType());
break;
}
}
return Proxy.NO_PROXY;
}
@Override
public void actionPerformed(ActionEvent actionEvent) {
int returnVal = fileChooser.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
Path proxyFile = fileChooser.getSelectedFile().toPath();
LambdaAttack.getLogger().log(Level.INFO, "Opening: {0}.", proxyFile.getFileName());
botManager.getThreadPool().submit(() -> {
try {
List<Proxy> proxies = Files.lines(proxyFile).distinct().map((line) -> {
String host = line.split(":")[0];
int port = Integer.parseInt(line.split(":")[1]);
InetSocketAddress address = new InetSocketAddress(host, port);
return new Proxy(Type.SOCKS, address);
}).collect(Collectors.toList());
LambdaAttack.getLogger().log(Level.INFO, "Loaded {0} proxies", proxies.size());
botManager.setProxies(proxies);
} catch (Exception ex) {
LambdaAttack.getLogger().log(Level.SEVERE, null, ex);
}
});
}
}
private Proxy getProxyFromProxyData(IProxyData proxyData) throws UnknownHostException {
Type proxyType;
if (IProxyData.HTTP_PROXY_TYPE.equals(proxyData.getType())) {
proxyType = Type.HTTP;
} else if (IProxyData.SOCKS_PROXY_TYPE.equals(proxyData.getType())) {
proxyType = Type.SOCKS;
} else if (IProxyData.HTTPS_PROXY_TYPE.equals(proxyData.getType())) {
proxyType = Type.HTTP;
} else {
throw new IllegalArgumentException("Invalid proxy type " + proxyData.getType());
}
InetSocketAddress sockAddr = new InetSocketAddress(InetAddress.getByName(proxyData.getHost()), proxyData.getPort());
Proxy proxy = new Proxy(proxyType, sockAddr);
if (!Strings.isNullOrEmpty(proxyData.getUserId())) {
Authenticator.setDefault(new ProxyAuthenticator(proxyData.getUserId(), proxyData.getPassword()));
}
return proxy;
}
/**
* 初始化HTTP代理服务器
*/
private void initHttpProxy() {
// 初始化代理服务器
if (httpProxyHost != null && httpProxyPort != null) {
SocketAddress sa = new InetSocketAddress(httpProxyHost, httpProxyPort);
proxy = new Proxy(Type.HTTP, sa);
// 初始化代理服务器的用户验证
if (httpProxyUsername != null && httpProxyPassword != null) {
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(httpProxyUsername, httpProxyPassword.toCharArray());
}
});
}
}
}
/**
* 初始化HTTP代理服务器
*/
private void initHttpProxy() {
// 初始化代理服务器
if (httpProxyHost != null && httpProxyPort != null) {
SocketAddress sa = new InetSocketAddress(httpProxyHost, httpProxyPort);
proxy = new Proxy(Type.HTTP, sa);
// 初始化代理服务器的用户验证
if (httpProxyUsername != null && httpProxyPassword != null) {
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(httpProxyUsername, httpProxyPassword.toCharArray());
}
});
}
}
}
public static void init(boolean useProxy_, String type_, String ip_, String port_, String username_, String pwd_){
useProxy = useProxy_;
ip = ip_;
port = port_;
username = username_;
pwd = pwd_;
if("ie".equals(type_)){
useIEProxy = true;
}else{
useIEProxy = false;
if("http".equals(type_)){
type = java.net.Proxy.Type.HTTP;
}
//jdk6的socks4代理存在bug
else if("socks".equals(type_)){
type = java.net.Proxy.Type.SOCKS;
}
//proxy();
}
}
public static java.net.Proxy getNetProxy(){
if(useProxy){
if(useIEProxy){
String[] ieproxys = getIEProxy();
if(ieproxys != null){
//取第一个代理设置
String[] arr = ieproxys[0].split("=");
if(arr.length == 2){
Type type = null;
String[] hostport = arr[1].split(":");
if(hostport.length == 2){
if(arr[0].equals("http")){
type = java.net.Proxy.Type.HTTP;
}else if(arr[0].equals("socks")){
type = java.net.Proxy.Type.SOCKS;
}
return new java.net.Proxy(type, new InetSocketAddress(hostport[0], Integer.parseInt(hostport[1])));
}
}
}
}else{
return new java.net.Proxy(type, new InetSocketAddress(ip, Integer.parseInt(port)));
}
}
return null;
}
/**
* Define the proxy to use for all GA tracking requests.
* <p>
* Call this static method early (before creating any tracking requests).
*
* @param proxyAddr
* "addr:port" of the proxy to use; may also be given as URL
* ("http://addr:port/").
*/
public static void setProxy(String proxyAddr)
{
if(proxyAddr != null)
{
// Split into "proxyAddr:proxyPort".
proxyAddr = null;
int proxyPort = 8080;
try(Scanner s = new Scanner(proxyAddr))
{
s.findInLine("(http://|)([^:/]+)(:|)([0-9]*)(/|)");
MatchResult m = s.match();
if(m.groupCount() >= 2)
proxyAddr = m.group(2);
if(m.groupCount() >= 4 && !(m.group(4).length() == 0))
proxyPort = Integer.parseInt(m.group(4));
}
if(proxyAddr != null)
{
SocketAddress sa = new InetSocketAddress(proxyAddr, proxyPort);
setProxy(new Proxy(Type.HTTP, sa));
}
}
}
private static Proxy proxyFromHostPort(Proxy.Type type, String hostPortString) {
try {
String[] hostPort = hostPortString.split(":");
String host = hostPort[0];
int port = Integer.parseInt(hostPort[1]);
return new Proxy(type, InetSocketAddress.createUnresolved(host, port));
} catch (NumberFormatException|ArrayIndexOutOfBoundsException e) {
Log.d(TAG, "Unable to parse proxy " + hostPortString + " " + e);
return null;
}
}
/**
* Define the proxy to use for all GA tracking requests.
* <p>
* Call this static method early (before creating any tracking requests).
*
* @param proxyAddr
* "addr:port" of the proxy to use; may also be given as URL
* ("http://addr:port/").
*/
public static void setProxy(String proxyAddr)
{
if(proxyAddr != null)
{
// Split into "proxyAddr:proxyPort".
proxyAddr = null;
int proxyPort = 8080;
try(Scanner s = new Scanner(proxyAddr))
{
s.findInLine("(http://|)([^:/]+)(:|)([0-9]*)(/|)");
MatchResult m = s.match();
if(m.groupCount() >= 2)
proxyAddr = m.group(2);
if(m.groupCount() >= 4 && !(m.group(4).length() == 0))
proxyPort = Integer.parseInt(m.group(4));
}
if(proxyAddr != null)
{
SocketAddress sa = new InetSocketAddress(proxyAddr, proxyPort);
setProxy(new Proxy(Type.HTTP, sa));
}
}
}
private HttpURLConnection openConnection ( final URL url ) throws IOException
{
final String host = this.properties.getProperty ( "local.proxy.host" );
final String port = this.properties.getProperty ( "local.proxy.port" );
if ( host != null && port != null && !host.isEmpty () && !port.isEmpty () )
{
final Proxy proxy = new Proxy ( Type.HTTP, new InetSocketAddress ( host, Integer.parseInt ( port ) ) );
return (HttpURLConnection)url.openConnection ( proxy );
}
else
{
return (HttpURLConnection)url.openConnection ();
}
}
private HttpURLConnection openConnection ( final URL url ) throws IOException
{
final String host = this.properties.getProperty ( "local.proxy.host" );
final String port = this.properties.getProperty ( "local.proxy.port" );
if ( host != null && port != null && !host.isEmpty () && !port.isEmpty () )
{
final Proxy proxy = new Proxy ( Type.HTTP, new InetSocketAddress ( host, Integer.parseInt ( port ) ) );
return (HttpURLConnection)url.openConnection ( proxy );
}
else
{
return (HttpURLConnection)url.openConnection ();
}
}
@Test
public void testConstructorWithProxy() throws MalformedURLException, IOException {
Proxy proxy =
new Proxy(Type.HTTP,
new InetSocketAddress(proxyServer.getHostname(), proxyServer.getPort()));
HttpURLConnection connection =
new TimeoutAwareConnectionFactory(proxy).openConnection(new URL(NONEXISTENTDOMAIN));
connectReadAndDisconnect(connection);
}
@Test
public void testConstructorWithProxyAndTimeouts() throws MalformedURLException, IOException {
Proxy proxy =
new Proxy(Type.HTTP,
new InetSocketAddress(proxyServer.getHostname(), proxyServer.getPort()));
HttpURLConnection connection =
new TimeoutAwareConnectionFactory(proxy, 1764, 3528)
.openConnection(new URL(NONEXISTENTDOMAIN));
connectReadAndDisconnect(connection);
assertThat(connection.getConnectTimeout(), is(1764));
assertThat(connection.getReadTimeout(), is(3528));
}
private static Proxy getProxy ( final String url )
{
final ProxySelector ps = ProxySelector.getDefault ();
if ( ps == null )
{
logger.debug ( "No proxy selector found" );
return null;
}
final List<java.net.Proxy> proxies = ps.select ( URI.create ( url ) );
for ( final java.net.Proxy proxy : proxies )
{
if ( proxy.type () != Type.HTTP )
{
logger.debug ( "Unsupported proxy type: {}", proxy.type () );
continue;
}
final SocketAddress addr = proxy.address ();
logger.debug ( "Proxy address: {}", addr );
if ( ! ( addr instanceof InetSocketAddress ) )
{
logger.debug ( "Unsupported proxy address type: {}", addr.getClass () );
continue;
}
final InetSocketAddress inetAddr = (InetSocketAddress)addr;
return new Proxy ( Proxy.TYPE_HTTP, inetAddr.getHostString (), inetAddr.getPort () );
}
logger.debug ( "No proxy found" );
return null;
}
private Proxy createProxyAddress(final URL proxy) {
if (proxy == null) return null;
String host = proxy.getHost();
int port = proxy.getPort();
if (port < 0) {
port = proxy.getDefaultPort();
}
return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
}
/**
* Define the proxy to use for all GA tracking requests.
* <p>
* Call this static method early (before creating any tracking requests).
*
* @param proxyAddr
* "addr:port" of the proxy to use; may also be given as URL
* ("http://addr:port/").
*/
public static void setProxy(String proxyAddr)
{
if(proxyAddr != null)
{
Scanner s = new Scanner(proxyAddr);
// Split into "proxyAddr:proxyPort".
proxyAddr = null;
int proxyPort = 8080;
try
{
s.findInLine("(http://|)([^:/]+)(:|)([0-9]*)(/|)");
MatchResult m = s.match();
if(m.groupCount() >= 2)
proxyAddr = m.group(2);
if(m.groupCount() >= 4 && !(m.group(4).length() == 0))
proxyPort = Integer.parseInt(m.group(4));
}finally
{
s.close();
}
if(proxyAddr != null)
{
SocketAddress sa = new InetSocketAddress(proxyAddr, proxyPort);
setProxy(new Proxy(Type.HTTP, sa));
}
}
}
public MojangSkinApi(Logger logger, int rateLimit, Collection<HostAndPort> proxies) {
this.logger = logger;
this.rateLimiter = new RateLimiter(Duration.ofMinutes(10), Math.max(rateLimit, 600));
Set<Proxy> proxyBuilder = proxies.stream()
.map(proxy -> new InetSocketAddress(proxy.getHostText(), proxy.getPort()))
.map(sa -> new Proxy(Type.HTTP, sa))
.collect(toSet());
this.proxies = Iterables.cycle(proxyBuilder).iterator();
}
private Proxy[] getProxies() {
String proxyString = authority.getProxyString();
if (!StringUtils.isEmpty(proxyString)) {
java.net.Proxy proxy = FileUtils.getProxy(authority.getProxyString());
if ((proxy != null) && (proxy.type() != Type.DIRECT)) {
URI proxyUri = URI.create(proxyString);
String hostName = proxyUri.getHost();
int port = proxyUri.getPort();
String userInfo = proxyUri.getUserInfo();
org.jetel.util.protocols.UserInfo proxyCredentials = null;
if (userInfo != null) {
proxyCredentials = new org.jetel.util.protocols.UserInfo(userInfo);
}
switch (proxy.type()) {
case HTTP:
ProxyHTTP proxyHttp = (port >= 0) ? new ProxyHTTP(hostName, port) : new ProxyHTTP(hostName);
if (proxyCredentials != null) {
proxyHttp.setUserPasswd(proxyCredentials.getUser(), proxyCredentials.getPassword());
}
return new Proxy[] {proxyHttp};
case SOCKS:
ProxySOCKS4 proxySocks4 = (port >= 0) ? new ProxySOCKS4(hostName, port) : new ProxySOCKS4(hostName);
ProxySOCKS5 proxySocks5 = (port >= 0) ? new ProxySOCKS5(hostName, port) : new ProxySOCKS5(hostName);
if (proxyCredentials != null) {
proxySocks4.setUserPasswd(proxyCredentials.getUser(), proxyCredentials.getPassword());
proxySocks5.setUserPasswd(proxyCredentials.getUser(), proxyCredentials.getPassword());
}
return new Proxy[] {proxySocks5, proxySocks4};
case DIRECT:
return new Proxy[1];
}
}
}
return new Proxy[1];
}
public void testGetProxy() {
testGetProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("hostname.com", 8080)), "proxy://hostname.com:8080");
testGetProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("hostname.com", 8080)), "proxy://hostname.com"); // default port
testGetProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("hostname", 3128)), "proxy://user:p%[email protected]:3128");
testGetProxy(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("hostname.com", 8080)), "proxysocks://hostname.com:8080");
testGetProxy(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("hostname.com", 8080)), "proxysocks://hostname.com"); // default port
testGetProxy(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("hostname", 3128)), "proxysocks://user:p%[email protected]stname:3128");
testGetProxy(Proxy.NO_PROXY, "direct:");
testGetProxy(null, "");
testGetProxy(null, null);
testGetProxy(null, "ftp://hostname.com");
}
/**
* @return the proxy settings
*/
public Proxy getProxy() {
LeoObject proxy = this.config.get("master_server", "proxy_settings");
if(LeoObject.isTrue(proxy)) {
Proxy p = new Proxy(Type.HTTP, new InetSocketAddress(this.config.getString("master_server", "proxy_settings", "address"),
this.config.getInt(88, "master_server", "proxy_settings", "port")));
return (p);
}
return Proxy.NO_PROXY;
}
public Proxy toProxy() {
if (hasValidProxySettings()) {
switch (type) {
case HTTP:
case HTTPS:
return new Proxy(Type.HTTP, new InetSocketAddress(host, port));
case SOCKS:
return new Proxy(Type.SOCKS, new InetSocketAddress(host, port));
}
}
return null;
}
@Before
public void setUp() {
Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(PROXY_SERVER_HOST, PROXY_SERVER_PORT));
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setProxy(proxy);
restTemplate = new RestTemplate(requestFactory);
}
/**
*
* Sets the proxy host and port. This will be implicitly called if
* "proxy.host" and "proxy.port" properties are given in properties file
*
* @param host
* proxy host
* @param port
* proxy port
*/
public static void setProxyConfig(final String host, final int port) {
if (host != null) {
int proxyPort = port;
if (proxyPort < 0) {
proxyPort = 0;
}
LOG.debug("Setting proxy - Host : " + host + " port : " + port);
proxyObj = new Proxy(Type.HTTP, new InetSocketAddress(host, port));
}
}
/**
* Test that the proxy is being used, but don't check the credentials. Credentials can still be
* used, but they must be set using the appropriate system properties and testing that is not what
* we are looking to do here.
*/
@Test
public void canCreateWithImplicitOrNoCredentials() throws Exception {
Proxied proxied = new Proxied(
TrustingSSLSocketFactory.get(), null,
new Proxy(Type.HTTP, proxyAddress));
assertThat(proxied).isNotNull();
assertThat(proxied.getCredentials()).isNullOrEmpty();
/* verify that the proxy */
HttpURLConnection connection = proxied.getConnection(new URL("http://www.example.com"));
assertThat(connection).isNotNull().isInstanceOf(HttpURLConnection.class);
}
@Test
public void canCreateWithExplicitCredentials() throws Exception {
Proxied proxied = new Proxied(
TrustingSSLSocketFactory.get(), null,
new Proxy(Type.HTTP, proxyAddress), "user", "password");
assertThat(proxied).isNotNull();
assertThat(proxied.getCredentials()).isNotBlank();
HttpURLConnection connection = proxied.getConnection(new URL("http://www.example.com"));
assertThat(connection).isNotNull().isInstanceOf(HttpURLConnection.class);
}
/**
* Tests select(URI) HTTP
*/
@Test
public void testSelect_HTTP() throws UnknownHostException {
systemProperties.setProperty(HTTP_PROXY_HOST, LOCALHOST);
systemProperties.setProperty(HTTP_PROXY_PORT, TEST_PORT_STR);
JaxWsProxySelector ps = new JaxWsProxySelector(ProxySelector.getDefault(), systemProperties);
ProxySelector.setDefault(ps);
List<Proxy> list = ps.select(testHttpUri);
assertEquals(list.get(0),
new Proxy(Type.HTTP,
new InetSocketAddress(InetAddress.getByName(LOCALHOST), TEST_PORT_NUM)));
}