代码示例-Java
发布时间:2021-08-03 21:04
Java HttpURLConnection
package com.qgproxy;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.URL;
class QGProxyAuthenticator extends Authenticator {
private String user, password;
public QGProxyAuthenticator(String user, String password) {
this.user = user;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password.toCharArray());
}
}
class QGProxy {
public static void main(String args[]) {
// 如果您的本地jdk版本在Java 8 Update 111以上,需要增加以下代码
// System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "false");
// System.setProperty("jdk.http.auth.proxying.disabledSchemes", "false");
String targetUrl = "https://ip.cn/api/index?ip=&type=0";
String proxyIp = "您的代理IP";
int proxyPort = 端口号;
String authKey = "请改成您的Key";
String password = "请改成您的AuthPwd";
try {
URL url = new URL(targetUrl);
Authenticator.setDefault(new QGProxyAuthenticator(authKey, password));
InetSocketAddress socketAddress = new InetSocketAddress(proxyIp, proxyPort);
Proxy proxy = new Proxy(Proxy.Type.HTTP, socketAddress);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
byte[] response = readStream(connection.getInputStream());
System.out.println(new String(response));
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
}
public static byte[] readStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = inStream.read(buffer)) != -1) {
outSteam.write(buffer, 0, len);
}
outSteam.close();
inStream.close();
return outSteam.toByteArray();
}
}
Java okhttp
package com.qgproxy;
import okhttp3.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.concurrent.TimeUnit;
public class QGProxy {
final static String proxyIp = "您的代理IP";
final static Integer proxyPort = 端口号;
final static String authKey = "请改成您的Key";
final static String password = "请改成您的AuthPwd";
public Response request() throws IOException {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIp, proxyPort));
OkHttpClient client = new OkHttpClient.Builder()
.proxy(proxy)
.proxyAuthenticator((route, response) -> {
String credential = Credentials.basic(authKey, password);
return response.request().newBuilder().header("Proxy-Authorization", credential).build();
}).
build();
Request request = new Request.Builder().url("https://ip.cn/api/index?type=0").get().build();
return client.newCall(request).execute();
}
public static void main(String[] args) {
QGProxy qgProxy = new QGProxy();
try {
Response resp = qgProxy.request();
System.out.println(resp.body().string());
} catch (Exception e) {
System.out.printf("failed to proxy: %s\n", e.getMessage());
}
}
}
Java jsonp
package com.qgproxy;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
public class QGProxy {
final static String proxyIp = "您的代理IP";
final static Integer proxyPort = 端口号;
final static String authKey = "请改成您的Key";
final static String password = "请改成您的AuthPwd";
public static void main(String[] args) throws Exception {
String targetUrl = "https://ip.cn/api/index?ip=&type=0";
Authenticator.setDefault(new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(authKey, password.toCharArray());
}
});
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIp, proxyPort));
try {
Document doc = Jsoup.connect(url).timeout(10000).proxy(proxy).get();
if (doc != null) {
System.out.println(doc.body().html());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Java HttpClient 3.X
package com.qgproxy;
import java.io.IOException;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class QGProxy {
public static void main(String[] args) {
String targetUrl = "ip.cn/api/index?ip=&type=0"; // 访问的目标站点
String proxyIp = "您的代理IP";
int proxyPort = 端口号;
String authKey = "请改成您的Key";
String password = "请改成您的AuthPwd";
try {
HttpHost proxy = new HttpHost(proxyIp, proxyPort, "http");
HttpHost target = new HttpHost(targetUrl, 80);
// 设置认证
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(authKey, password));
CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).build();
RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
HttpGet httpGet = new HttpGet("/ip");
httpGet.setConfig(config);
CloseableHttpResponse resp = null;
resp = httpClient.execute(target, httpGet);
if (resp.getStatusLine().getStatusCode() == 200) {
System.out.println("OK");
}
System.out.println(resp.getStatusLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Java HttpClient 4.X
package com.qgproxy
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.ProxyAuthenticationStrategy;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.NameValuePair;
import org.apache.http.util.EntityUtils;
public class QGProxy {
final static String proxyHost = "您的代理IP";
final static Integer proxyPort = 端口号;
final static String proxyUser = "请改成您的key";
final static String proxyPass = "请改成您的password";
private static PoolingHttpClientConnectionManager cm = null;
private static HttpRequestRetryHandler httpRequestRetryHandler = null;
private static HttpHost proxy = null;
private static CredentialsProvider credsProvider = null;
private static RequestConfig reqConfig = null;
static {
ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
Registry registry = RegistryBuilder.create()
.register("http", plainsf)
.register("https", sslsf)
.build();
cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(10);
cm.setDefaultMaxPerRoute(5);
proxy = new HttpHost(proxyHost, proxyPort, "http");
credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyUser, proxyPass));
reqConfig = RequestConfig.custom()
.setExpectContinueEnabled(false)
.setProxy(new HttpHost(proxyHost, proxyPort))
.build();
}
public static void doRequest(HttpRequestBase httpReq) {
CloseableHttpResponse httpResp = null;
try {
httpReq.setConfig(reqConfig);
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(cm)
.setDefaultCredentialsProvider(credsProvider)
.build();
AuthCache authCache = new BasicAuthCache();
authCache.put(proxy, new BasicScheme());
authCache.put(proxy, new BasicScheme(ChallengeState.PROXY));
HttpClientContext localContext = HttpClientContext.create();
localContext.setAuthCache(authCache);
httpResp = httpClient.execute(httpReq, localContext);
System.out.println(httpResp.getStatusLine().getStatusCode(););
BufferedReader rd = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));
String line = "";
while((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (httpResp != null) {
httpResp.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
String targetUrl = "https://ip.cn/api/index?ip=&type=0";
try {
HttpGet httpGet = new HttpGet(targetUrl);
doRequest(httpGet);
} catch (Exception e) {
e.printStackTrace();
}
}
}
相关文章