Java使用playwright调用Http代理IP的代码样例#
<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>1.40.0</version>
</dependency>
【白名单鉴权】使用示例 (推荐)#
import com.microsoft.playwright.*;
import com.microsoft.playwright.options.BrowserType;
public class PlaywrightProxyNoAuth {
// 目标网站
private static final String PAGE_URL = "http://api.youdaili.com/v1/tools/get-public-ip";
// 无需鉴权的代理配置
private static final String PROXY_IP = "your_proxy_ip"; // 使用时,需要换成真实的代理IP
private static final int PROXY_PORT = your_proxy_port; // 使用时,需要换成真实的代理端口
public static void main(String[] args) {
// 构建无需鉴权的代理URL(仅IP+端口)
String proxyUrl = String.format("http://%s:%d", PROXY_IP, PROXY_PORT);
try (Playwright playwright = Playwright.create()) {
System.out.printf("使用无需鉴权代理 %s 访问 %s...%n", proxyUrl, PAGE_URL);
// 1. 配置浏览器
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions()
.setHeadless(true)
.setTimeout(10000)
);
// 2. 配置浏览器上下文(无需鉴权,直接设置代理URL)
BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.setProxy(proxyUrl)
.setDefaultTimeout(15000)
);
// 3. 发起请求并处理响应
Page page = context.newPage();
Response response = page.navigate(PAGE_URL);
if (response.ok()) {
String responseContent = response.text();
System.out.println("请求成功!响应内容:");
System.out.println(responseContent);
} else {
System.err.printf("请求失败!状态码:%d,状态信息:%s%n",
response.status(), response.statusText());
}
// 4. 释放资源
page.close();
context.close();
browser.close();
} catch (PlaywrightException e) {
System.err.println("错误:Playwright执行异常!");
if (e.getMessage().contains("proxy")) {
System.err.println("原因:代理连接失败,请检查IP和端口");
} else if (e.getMessage().contains("timeout")) {
System.err.println("原因:请求超时");
} else {
System.err.println("原因:" + e.getMessage());
}
} catch (Exception e) {
System.err.println("错误:未知异常 - " + e.getMessage());
}
}
}
【账号密码鉴权】使用示例#
"鉴权账号"和"鉴权密码"均在会员后台->产品管理中对应的业务里查看