
/** * 使用指定代理测试连接并返回代理的外网 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