java OkHTTPClient Proxy 认证怎么做?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35554380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 00:17:02  来源:igfitidea点击:

OkHTTPClient Proxy authentication how to?

javaproxyokhttpokhttp3

提问by Liably

Question:How do I add a authorization proxy to OkHTTP.

问题:如何向 OkHTTP 添加授权代理。

I know that OkHTTP's builder does support proxiesalthough I am having a hard time setting one up.

我知道 OkHTTP 的构建器确实支持代理,尽管我很难设置代理

/**
 * Given a Url and a base64 encoded password return the contents of a website.
 * @param urlString
 * @param password
 * @return JSON
 */
public String getURLJson(String urlString, String password) {       
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();

        Request request = new Request.Builder()
          .url(urlString)
          .get()
          .addHeader("authorization", "Basic " + password)
          .addHeader("cache-control", "no-cache")
          .build();

        Response response = null;
        try {
            response = client.newCall(request).execute();
            String string = response.body().string();
            response.body().close();
            return string;
        } catch (IOException e) {
            System.err.println("Failed scraping");
            e.printStackTrace();
        }
        return "failed";
    }

I have the IP / port / username / password.

我有IP/端口/用户名/密码。

Although I do not know how to turn those into a Proxy proxywhich can then be used in client.SetProxy().

虽然我不知道如何将它们转换为Proxy proxy可以在 client.SetProxy() 中使用的。

It seems overly complicated and I simply can't seem to figure it out. Any help would be appreciated.

这似乎过于复杂,我似乎无法弄清楚。任何帮助,将不胜感激。

回答by Jesse Wilson

Try this:

试试这个:

int proxyPort = 8080;
String proxyHost = "proxyHost";
final String username = "username";
final String password = "password";

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

OkHttpClient client = new OkHttpClient.Builder()
    .connectTimeout(60, TimeUnit.SECONDS)
    .writeTimeout(60, TimeUnit.SECONDS)
    .readTimeout(60, TimeUnit.SECONDS)
    .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)))
    .proxyAuthenticator(proxyAuthenticator)
    .build();