作者: yiniuyun0
查看: 1432|回复: 0

[讨论] JSoup程序中使用代理

[复制链接]
yiniuyun0 发表于 2019-7-15 17:41:04 | 显示全部楼层 |阅读模式
查看: 1432|回复: 0

import java.io.IOException;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import org.jsoup.Jsoup
;import org.jsoup.nodes.Document;
public class Demo{
    // 代理隧道验证信息
    final static String ProxyUser = "16KASDA";
    final static String ProxyPass = "1231321";
    // 代理服务器
    final static String ProxyHost = "t.16yun.cn";
    final static Integer ProxyPort = 31111;
    // 设置IP切换头
    final static String ProxyHeadKey = "Proxy-Tunnel";
    public static String getUrlProxyContent(String url)
    {
        Authenticator.setDefault(new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication(ProxyUser, ProxyPass.toCharArray());
            }
        });
        // 设置Proxy-Tunnel
        Random random = new Random();
        int tunnel = random.nextInt(10000);
        String ProxyHeadVal = String.valueOf(tunnel);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ProxyHost, ProxyPort));
        try
        {
            // 处理异常、其他参数
            Document doc = Jsoup.connect(url).timeout(3000).header(ProxyHeadKey, ProxyHeadVal).proxy(proxy).get();
            if(doc != null) {
                System.out.println(doc.body().html());
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    public static void main(String[] args) throws Exception
    {
        // 要访问的目标页面
        String targetUrl = "http://httpbin.org/ip";
        getUrlProxyContent(targetUrl);
    }}

回复 论坛版权

使用道具 举报

您需要登录后才可以回帖 登录 | 加入CSkin博客

本版积分规则

QQ|申请友链|小黑屋|手机版|Archiver|CSkin ( 粤ICP备13070794号

Powered by Discuz! X3.2  © 2001-2013 Comsenz Inc.  Designed by ARTERY.cn
GMT+8, 2024-4-17 07:11, Processed in 0.558497 second(s), 30 queries , Gzip On.

快速回复 返回顶部 返回列表