Android okhttp3设置代理(http/https)

由于项目需要通过代理验证方式进行演示,尝试通过手机设置进行代理设置。但由于代理需要进行账号密码验证,导致请求报错。

java.io.IOException: Failed to authenticate with proxy

所以采用代码配置代理。

    //代理验证的账号及密码
    final String userName = "";
    final String password = "";
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            //代理服务器的IP和端口号
            .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8080)))
            代理的鉴权账号密码
            .proxyAuthenticator(new Authenticator() {
                @Override
                public Request authenticate(Route route, Response response) throws IOException {
                    //设置代理服务器账号密码
                    String credential = Credentials.basic(username, password);
                    return response.request().newBuilder()
                            .header("Proxy-Authorization", credential)
                            .build();
                }
            })
            .build();

你可能感兴趣的:(Android,http,网络协议,网络)