美文网首页
检查okhttp代理是否正常工作

检查okhttp代理是否正常工作

作者: fzhyzamt | 来源:发表于2019-07-11 15:49 被阅读0次
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.net.InetAddresses;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.apache.commons.lang3.StringUtils;
import static com.google.common.base.Preconditions.checkNotNull;

 public boolean checkProxy(OkHttpClient client) throws IOException {
        Proxy proxy = checkNotNull(client.proxy());
        String proxyIP = proxy.address().toString().split(":")[0];
        if (!isInetAddress(proxyIP)) {
            // host -> ip
            proxyIP = InetAddress.getByName(proxyIP).getHostAddress();
        }
        if (proxyIP.equals("127.0.0.1")) {
            logger.warn("use local proxy: {}", proxy);
            return true;
        }
        Request req = new Request.Builder()
                .url("https://httpbin.org/get")
                .build();

        JsonNode jsonNode = objectMapper.readTree(client.newCall(req).execute().body().string());
        String origin = jsonNode.get("origin").asText();
        for (String ip : StringUtils.split(origin, ',')) {
            if (!proxyIP.equals(ip.trim())) {
                return false;
            }
        }
        return true;
    }

相关文章

网友评论

      本文标题:检查okhttp代理是否正常工作

      本文链接:https://www.haomeiwen.com/subject/khddkctx.html