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;
}
网友评论