[Java] 纯文本查看 复制代码
import okhttp3.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.concurrent.TimeUnit;
public class OkHttp {
// 代理服务器(产品官网 www.16yun.cn)
final static String proxyHost = "t.16yun.cn";
final static Integer proxyPort = 31111;
// 代理验证信息
final static String proxyUser = "USERNAME";
final static String proxyPass = "PASSWORD";
static OkHttpClient client = null;
static {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
Authenticator proxyAuthenticator = new Authenticator() {
public Request authenticate(Route route, Response response) {
String credential = Credentials.basic(proxyUser, proxyPass);
return response.request().newBuilder()
.header("Proxy-Authorization", credential)
.build();
}
};
client = new OkHttpClient().newBuilder()
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.proxy(proxy)
.proxyAuthenticator(proxyAuthenticator)
.connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS))
.build();
}
public static Response doGet() throws IOException {
// 要访问的目标页面
String targetUrl = "http://httpbin.org/ip";
Request request = new Request.Builder()
.url(targetUrl)
.build();
Response response = client.newCall(request).execute();
return response;
}
public static void main(String[] args) throws IOException {
Response response1 = doGet();
System.out.println("GET请求返回结果:");
System.out.println(response1.body().string());
}
}