获取代理IP
## 1 API调用提取
对于短效代理、独享代理、长效代理,我们都提供了API接口,方便开发者批量获取代理IP。
接口返回数据的格式支持文本、json、xml。
获取IP接口文档:
- [短效代理IP资源提取 >](https://www.qg.net/doc/2255.html)
- [独享代理IP资源提取 >](https://www.qg.net/doc/1840.html)
- [长效代理IP资源提取 >](https://www.qg.net/doc/1863.html)
隧道代理无需调用API提取代理,其他接口参见:[API接口概览](https://www.qg.net/doc/2145.html)
## 2 生成API链接
你可以在【提取工具】或【调试工具】生成API链接在线提取IP,方便集成到您的程序或软件中。
### 2.1 提取工具
选择已购买可用的AuthKey值,根据实际需求提取对应的IP,点击【生成链接】获取在线API链接,【打开链接】新窗口打开获取申请成功的IP信息,如下图所示;


### 2.2 调试工具
首先勾选要进行提取的业务key,key为必选项,是对接接口的必要信息;
其次,选择接口方法,不同的产品可选择的提取接口不同。
短效代理可选择【提取IP资源】、【获取IP池资源】接口,接口【获取IP池资源】是获取IP资源池全部可用的IP,资源池指的是购买短效代理的多通道形成的小资源池;
独享代理提取接口可选择【提取IP资源】、【更换IP资源】,接口【更换IP资源】是释放IP并申请新的IP;
长效代理提取接口可选择【提取IP资源】;
然后,其他选项IP数量、地区、运营商按需选择,最后点击【测试】按钮即可进行IP提取,申请成功返回结果为如下图所示;

## 3 测试API链接
### 3.1 浏览器测试
您可以把生成的API链接直接在浏览器里打开,查看返回结果。例如,您直接点击如下api链接:
https://proxy.qg.net/query?Key=0B***607
###3.2 命令行测试
如果您在linux系统下,可以通过curl命令请求API链接查看结果:
```
curl "https://proxy.qg.net/allocate?Key=请改成您的Key
```
## 4 接口返回错误码
| 错误码 | 描述 |
| ------------ | ------------ |
| -1 | 未知错误 |
| -10 | 参数不合法 |
| -11 | 请求过于频繁 |
| -100 | 计划不存在或已过期 |
| -101 | 请求数量超过计划通道数 |
| -102 | 没有剩余的可用通道 |
| -103 | 资源不足 |
| -104 | 资源申请失败 |
| -105 | 申请的IP数超过允许申请的IP数 |
每个接口自己的错误码请参见各接口文档。
## 5 代码样例
- [代码示例-Python](https://www.qg.net/doc/81.html)
- [代码示例-Java](https://www.qg.net/doc/82.html)
- [代码示例-PHP](https://www.qg.net/doc/83.html)
长效代理-API接口介绍
## 1说明
通过编码使用长效代理主要有以下4步骤:
1.先在[提取工具](https://www.qg.net/tools/IPget.html)或[调试工具](https://www.qg.net/tools/IPdebug.html)上获取api接口;
2.使用白名单或账密进行授权验证;
3.进行代理测试;[查看测试步骤>>](https://www.qg.net/doc/1574.html "查看测试步骤")
4.参考[代码样例](https://www.qg.net/list/192.html)编写采集程序,使用代理IP。
## 2 API接口
长效代理API接口一览
| 接口类型 | API | 描述 |
| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| 资源相关 | - [get](https://www.qg.net/doc/product/6_258_274/1863.html)
- [delete](https://www.qg.net/doc/product/6_258_274/1862.html)
- [query](https://www.qg.net/doc/product/6_258_274/1861.html)
- [channels](https://www.qg.net/doc/product/6_258_274/1860.html)
- [resources](https://www.qg.net/doc/product/6_258_274/1859.html)
| - 提取IP资源
- 释放IP资源
- 查询在用IP资源
- 查询通道数
- 查询资源地区
|
| 白名单相关 | -[whitelist/query](https://www.qg.net/doc/180.html "whitelist/query")
- [whitelist/add](https://www.qg.net/doc/178.html "whitelist/add")
- [whitelist/del](https://www.qg.net/doc/179.html "删除白名单")
| - 查询IP的白名单
- 添加IP的白名单
- 删除IP的白名单 |
使用青果网络远程插件登录Linux实例
# 1. 操作场景
本文介绍如何使用青果网络远程插件登录方式登录Linux实例。此处以PuTTY为例。
# 2. 适用本地操作系统
Windows
# 3. 前提条件
- 请先安装好其中一种本地远程工具:
- PuTTY:[立即下载](https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html)
- SecureCRT:[立即下载](https://www.vandyke.com/products/securecrt/)
- Xshell:[立即下载](https://www.xshellcn.com/xiazai.html)
# 3. 操作步骤
1. 登录[青果网络控制台](https://www.qg.net/user/)
2. 在对应的产品列表页中找到需要登录的业务实例,点击“登录”按钮
1. 在打开的远程登录窗口中,确认登录信息,并点击“登录”

1. 登录信息,系统会预先按照业务信息填写
2. 如果是初次使用,请先下载青果网络远程插件。[立即下载](https://storage.feikua.net/download/cloudremote/青果网络远程插件.zip)
2. 在浏览器中允许打开青果网络远程插件,即可登录成功。
3. 初次使用远程插件时,需要先配置本地工具的路径
1. 登录成功则出现类似如下图所示界面:
# 4. 常见问题
- 机器刚开通时,需要一定时间开机,请等待机器开机后,再尝试登录
使用青果网络远程插件登录Windows实例
# 1. 操作场景
本文介绍如何使用青果网络远程插件登录方式登录Windows实例。
# 2. 适用本地操作系统
Windows
# 3. 操作步骤
1. 登录[青果网络控制台](https://www.qg.net/user/)
2. 在对应的产品列表页中找到需要登录的业务实例,点击“登录”按钮
3. 在打开的远程登录窗口中,确认登录信息,并点击“登录”

1. 登录信息,系统会预先按照业务信息填写
2. 如果是初次使用,请先下载青果网络远程插件。[立即下载](https://storage.feikua.net/download/cloudremote/青果网络远程插件.zip)
4. 在浏览器中允许打开青果网络远程插件,即可登录成功。
1. 登录成功则出现类似如下图所示界面:
# 4. 常见问题
- 机器刚开通时,需要一定时间开机,请等待机器开机后,再尝试登录
Node语言代码示例
## nodejs http
```javascript
const http = require("http");
const url = require("url");
const targetURL = url.parse("https://test.ipw.cn");
// 如果上面目标站不可用,请使用ip.sb、ipinfo.io、ip-api.com、64.ipcheck.ing
const proxyIp = "您的代理IP";
const proxyPort = 端口号;
const authKey = "请改成您的Key";
const password = "请改成您的AuthPwd";
const base64 = new Buffer.from(authKey + ":" + password).toString("base64");
const options = {
host: proxyIp,
port: proxyPort,
path: targetURL,
method: "GET",
headers: {
"Host": urlParsed.hostname,
"Proxy-Authorization": "Basic " + base64
}
};
http.request(options, function (resp) {
console.log("response status code: " + resp.statusCode);
resp.pipe(process.stdout);
}).on("error", function (err) {
console.log("request failed: " + err);
}).end();
```
## nodejs request
```javascript
const request = require("https://test.ipw.cn");
// 如果上面目标站不可用,请使用ip.sb、ipinfo.io、ip-api.com、64.ipcheck.ing
const targetUrl = "https://api.ipify.org";
const proxyIp = "您的代理IP";
const proxyPort = 端口号;
const authKey = "请改成您的Key";
const password = "请改成您的AuthPwd";
const proxyUrl = "http://" + authKey + ":" + password + "@" + proxyIp + ":" + proxyPort;
const req = request.defaults({'proxy': proxyUrl});
const options = {
url: targetUrl,
headers: {}
};
req.get(options, function (err, resp, body) {
if (err) {
return console.log(err);
}
console.log("response status code: " + resp.statusCode);
console.log("response body: " + body);
}).on("error", function (err) {
console.log("request failed: " + err);
});
```
## nodejs superagent
```javascript
const request = require("superagent");
require("superagent-proxy")(request);
const targetUrl = "https://test.ipw.cn";
// 如果上面目标站不可用,请使用ip.sb、ipinfo.io、ip-api.com、64.ipcheck.ing
const proxyIp = "您的代理IP";
const proxyPort = 端口号;
const authKey = "请改成您的Key";
const password = "请改成您的AuthPwd";
const proxyUrl = "http://" + authKey + ":" + password + "@" + proxyIp + ":" + proxyPort;
request.get(targetUrl).proxy(proxyUrl).end(function onResponse(err, resp) {
if (err) {
return console.log(err);
}
console.log("response status code: " + resp.statusCode);
console.log("response body: " + resp.text);
});
```
## nodejs axios
```javascript
const axios = require("axios")
const {HttpsProxyAgent} = require("https-proxy-agent")
const targetUrl = "https://test.ipw.cn"
// 如果上面目标站不可用,请使用ip.sb、ipinfo.io、ip-api.com、64.ipcheck.ing
const proxyIp = "您的代理IP"
const proxyPort = 端口号
const authKey = "请改成您的Key"
const password = "请改成您的AuthPwd"
const proxy = new HttpsProxyAgent(`http://${authKey}:${password}@${proxyIp}:${proxyPort}`)
axios.get(targetUrl, {
httpAgent: proxy,
httpsAgent: proxy,
}).then(function (response) {
console.log("response body: " + response.data)
}).catch(function (error) {
console.log("request failed: " + error)
}).finally(function () {
console.log("request finished.")
})
// 如果目标站是HTTPS,则需要使用下面的代码进行代理请求
let httpsProxyAgent = require('https-proxy-agent');
var agent = new HttpsProxyAgent(`http://${authKey}:${password}@${proxyIp}:${proxyPort}`);
var config = {
url: "https://api.ipify.org",
httpsAgent: agent
}
axios.request(config)
.then(function(response) {
console.log("response body: " + response.data)
}).catch(function(error) {
console.log("request failed: " + error)
})
```
隧道代理 Go 语言接入指南
## 概述
本文档将指引你进行隧道代理的接入,在此文档中使用到的术语将会在下方进行列出。
| 术语 | 解释 |
| :------- | :----------------------------------------- |
| 隧道 | 自动更换代理 IP 的代理服务 |
| 固定时长 | 服务器将在固定时长后自动切换IP,例如1分钟 |
| 通道 | 使用多个通道同时发起请求,每个通道的IP不同 |
隧道代理有多种使用方式,具体行为取决于套餐及模式。
- 普通模式
每次请求都自动切换IP
- 普通模式打标记
普通模式下,希望多个HTTP请求保证代理IP相同,可以给多个请求的代理协议打上相同的标记,并标记这个代理IP的存活时间(不主动设置存活时间则默认为10秒)
- 固定时长多通道模式
服务器定时切换IP,可同时使用多个通道发起请求,即可以同时使用多个IP
## 前置知识
在 go 语言中,通常使用 http.Client 进行 http/s 代理的设定与请求的发送,使用 http.NewRequest 进行请求的构建。
### Proxy Url Scheme
由协议、用户名、密码、域名、端口几部分组成
例如 http 协议的代理 url
```
http://[user:password@]hostname:port
```
## 使用 GO 接入
**以下内容假设读者具备基本的 Go 语言编程能力和对网络协议具有一定的了解。**
### 生成 url
普通模式
```go
link := fmt.Sprintf("http://%s:%s@%s", authKey, password, proxyServer)
proxyURL, _ := url.Parse(link)
```
普通模式打标记
```go
link := fmt.Sprintf("http://%s:%s:%s:%d@%s", authKey, password, "channel-1", 20, proxyServer)
proxyURL, _ := url.Parse(link)
```
固定时长多通道模式
```go
link := fmt.Sprintf("http://%s:%s:%s@%s", authKey, password, "channel-1", proxyServer)
proxyURL, _ := url.Parse(link)
```
### 构建 Client
后续将使用该 client 发起 request
```go
client := http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyURL),
},
}
```
### 构建 HTTP/s GET 请求
以 https://api.ipify.org 为例。
因为已确认参数合法,因此构建不会发生错误,无需处理错误。
```
request, _ := http.NewRequest("GET", "https://test.ipw.cn", nil)
// 如果上面目标站不可用,请使用ip.sb、ipinfo.io、ip-api.com、64.ipcheck.ing
```
### 执行已构建的 HTTP/s 请求
```go
response, err := client.Do(request)
if err != nil {
panic(err)
}
defer response.Body.Close()
```
### 读取响应实体
response.Body 是 io.Reader 类型,需要手动进行读取
```go
body, err := io.ReadAll(response.Body)
if err != nil {
panic(err)
}
fmt.Println(string(body))
```
## 示例代码
```go
package main
import (
"fmt"
"io"
"log"
"net/http"
"net/url"
)
const (
authKey = ""
password = ""
server = ""
channel = "channel-1"
)
func main() {
var link string
if channel == "" {
link = fmt.Sprintf("http://%s:%s@%s", authKey, password, server)
} else {
link = fmt.Sprintf("http://%s:%s:%s@%s", authKey, password, channel, server)
}
proxyURL, _ := url.Parse(link)
client := http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyURL),
},
}
request, _ := http.NewRequest("GET", "https://test.ipw.cn", nil)
// 如果上面目标站不可用,请使用ip.sb、ipinfo.io、ip-api.com、64.ipcheck.ing
response, err := client.Do(request)
if err != nil {
panic(err)
}
defer response.Body.Close()
body, err := io.ReadAll(response.Body)
if err != nil {
panic(err)
}
log.Println("response body", string(body))
}
```
C#语言代码示例
```c#
string targetUrl = "https://test.ipw.cn";
// 如果上面目标站不可用,请使用ip.sb、ipinfo.io、ip-api.com、64.ipcheck.ing
string proxyIp = "您的代理IP";
string proxyPort = "端口号";
string authKey = "请改成您的Key";
string password = "请改成您的AuthPwd";
WebProxy proxy = new WebProxy(string.Format("{0}:{1}", proxyIp, proxyPort), true);
proxy.Credentials = new NetworkCredential(authKey, password);
ServicePointManager.Expect100Continue = false;
var request = WebRequest.Create(targetUrl) as HttpWebRequest;
request.AllowAutoRedirect = true;
request.KeepAlive = true;
request.Method = "GET";
request.Proxy = proxy;
request.Timeout = 10000;
request.ServicePoint.ConnectionLimit = 16;
using (var resp = request.GetResponse() as HttpWebResponse)
using (var reader = new StreamReader(resp.GetResponseStream(), Encoding.UTF8)){
string htmlStr = reader.ReadToEnd();
}
```
Shell语言代码示例
```shell
#!/bin/bash
targetURL="https://test.ipw.cn"
# 如果上面目标站不可用,请使用ip.sb、ipinfo.io、ip-api.com、64.ipcheck.ing
proxyAddr="您的代理IP:端口号"
authKey="请改成您的Key"
password="请改成您的AuthPwd"
curl -x ${authKey}:${password}@${proxyAddr} ${targetURL} -vvvv
```
Java语言代码示例
## Java HttpURLConnection
```java
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://test.ipw.cn";
// 如果上面目标站不可用,请使用ip.sb、ipinfo.io、ip-api.com、64.ipcheck.ing
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(4.10.0版本以上)
```java
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://api.ipify.org").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 jsoup
```java
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://test.ipw.cn";
// 如果上面目标站不可用,请使用ip.sb、ipinfo.io、ip-api.com、64.ipcheck.ing
Authenticator.setDefault(new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(authKey, password.toCharArray());
}
});
// 如果您的本地jdk版本在Java 8 Update 111以上,需要增加以下代码
// System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "false");
// System.setProperty("jdk.http.auth.proxying.disabledSchemes", "false");
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIp, proxyPort));
try {
Document doc = Jsoup.connect(targetUrl).ignoreContentType(true).timeout(10000).proxy(proxy).get();
if (doc != null) {
System.out.println(doc.body().html());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
## Java HttpClient 3.X
```java
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 = "https://test.ipw.cn"; // 访问的目标站点
// 如果上面目标站不可用,请使用ip.sb、ipinfo.io、ip-api.com、64.ipcheck.ing
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
```java
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://api.ipify.org";
try {
HttpGet httpGet = new HttpGet(targetUrl);
doRequest(httpGet);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
PHP语言代码示例
## PHP curl
```php
/**
* 请求
*
* @param [type] $targetUrl 目标站点
* @param [type] $proxyIp 代理ip
* @param [type] $proxyPort 代理端口
* @param [type] $proxyUser AuthKey
* @param [type] $proxyPassword AuthPwd
* @return void
*/
function sendRequest($targetUrl, $proxyIp, $proxyPort, $proxyUser, $proxyPassword){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $targetUrl);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, $proxyPort);
curl_setopt($ch, CURLOPT_PROXYTYPE, 'HTTP');
curl_setopt($ch, CURLOPT_PROXY, $proxyIp);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyUser . ':' . $proxyPassword);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$data = sendRequest('https://test.ipw.cn', '请改成您的代理IP', 端口号, '请改成您的Key', '请改成您的AuthPwd');
// 如果上面目标站不可用,请使用ip.sb、ipinfo.io、ip-api.com、64.ipcheck.ing
var_dump($data);
```
## PHP stream
```php
/**
* 请求
*
* @param [type] $targetUrl 目标站点
* @param [type] $proxyIp 代理ip
* @param [type] $proxyPort 代理端口
* @param [type] $proxyUser AuthKey
* @param [type] $proxyPassword AuthPwd
* @return void
*/
function sendRequest($targetUrl, $proxyIp, $proxyPort, $proxyUser, $proxyPassword){
$proxyAuth = base64_encode($proxyUser . ":" . $proxyPassword);
$headers = implode("\r\n", [
"Proxy-Authorization: Basic {$proxyAuth}"
]);
// 目标站为https时需要
// $sniServer = parse_url($targetUrl, PHP_URL_HOST);
$options = [
"http" => [
"proxy" => $proxyIp . ':' . $proxyPort,
"header" => $headers,
"method" => "GET",
"request_fulluri" => true,
],
// 目标站为https时需要
// 'ssl' => array(
// 'SNI_enabled' => true,
// 'SNI_server_name' => $sniServer
// )
];
$context = stream_context_create($options);
$result = file_get_contents($targetUrl, false, $context);
return $result;
}
$data = sendRequest('https://test.ipw.cn', '请改成您的代理IP', 端口号, '请改成您的Key', '请改成您的AuthPwd');
// 如果上面目标站不可用,请使用ip.sb、ipinfo.io、ip-api.com、64.ipcheck.ing
var_dump($data);
```
## PHP GuzzleHttp
```PHP
/**
* 请求
*
* @param [type] $targetUrl 目标站点
* @param [type] $proxyIp 代理ip
* @param [type] $proxyPort 代理端口
* @param [type] $proxyUser AuthKey
* @param [type] $proxyPassword AuthPwd
* @return void
*/
function sendRequest($targetUrl, $proxyIp, $proxyPort, $proxyUser, $proxyPassword){
$client = new \GuzzleHttp\Client();
$proxyAuth = base64_encode($proxyUser . ":" . $proxyPassword);
$options = [
"proxy" => $proxyIp . ':' . $proxyPort,
"headers" => [
"Proxy-Authorization" => "Basic " . $proxyAuth
]
];
$result = $client->request('GET', $targetUrl, $options);
return $result->getBody()->getContents();
}
$data = sendRequest('https://test.ipw.cn', '请改成您的代理IP', 端口号, '请改成您的Key', '请改成您的AuthPwd');
# 如果上面目标站不可用,请使用ip.sb、ipinfo.io、ip-api.com、64.ipcheck.ing
var_dump($data);
```