V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
Mrdawu
V2EX  ›  程序员

检测 socks 代理报错: Cannot invoke " Java .net.InetAddress.getHostName()" because "remote" is null

  •  
  •   Mrdawu · 8 小时 48 分钟前 · 167 次点击

    /** * 使用指定代理测试连接并返回代理的外网 IP * * @param url 测试 URL * @param proxyType 代理类型( HTTP 或 SOCKS ) * @param gateIp 代理 IP * @param gatePort 代理端口 * @param username 代理用户名(可为 null ) * @param password 代理密码(可为 null ) * @return 代理的外网 IP 地址 * @throws IOException IO 异常 */ public static String testProxy(String url, ProxyType proxyType, String gateIp, int gatePort, String username, String password) throws IOException { Proxy proxy = new Proxy( proxyType == ProxyType.SOCKS ? Proxy.Type.SOCKS : Proxy.Type.HTTP, new InetSocketAddress(gateIp, gatePort) );

        if (proxyType == ProxyType.SOCKS) {
            Authenticator.setDefault(new Authenticator() {
                private final PasswordAuthentication authentication = new PasswordAuthentication(
                        username, password.toCharArray());
    
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return authentication;
                }
            });
        }
    
        OkHttpClient.Builder clientBuilder = new OkHttpClient().newBuilder().proxy(proxy);
    
        if (proxyType == ProxyType.HTTP && username != null && password != null) {
            clientBuilder.proxyAuthenticator((route, response) -> {
                String credential = Credentials.basic(username, password);
                return response.request().newBuilder()
                        .header("Proxy-Authorization", credential)
                        .build();
            });
        }
        clientBuilder.connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS);
        OkHttpClient client = clientBuilder.build();
    
        Request request = new Request.Builder().url(url).build();
        try (Response response = client.newCall(request).execute()) {
            if (response.body() != null) {
                String responseBody = response.body().string();
                JSONObject jsonObject = JSON.parseObject(responseBody);
                return jsonObject.getString("origin");
            } else {
                throw new IOException("响应体为空");
            }
        }
    }
    
    有没有大佬帮忙看下是为啥,本地运行正常,但是部署服务器就会报错 Cannot invoke "java.net.InetAddress.getHostName()" because "remote" is null
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1219 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 19ms · UTC 18:05 · PVG 02:05 · LAX 10:05 · JFK 13:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.