文章详情
接入指南 - 代码 - Java - OkHttp
import okhttp3.*;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.concurrent.TimeUnit;

public class OkHttp {

    // 代理服务器
    final static String proxyHost = "tunnel.quqiquqi.com";
    final static Integer proxyPort = 8600;

    // 代理隧道验证信息
    final static String proxyUser = "U0123456789";
    final static String proxyPass = "P0123456789";

    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://www.quqiquqi.com/test";

        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());
    }

}

          
发布时间:2021-10-02

在线客服