OkHTTPClient代理身份验证如何?

编程入门 行业动态 更新时间:2024-10-23 10:24:50
本文介绍了OkHTTPClient代理身份验证如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

我知道OkHTTP的生成器支持代理,尽管我有一个很难设置一个.

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

/** * 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"; }

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

I have the IP / port / username / password.

尽管我不知道如何将它们转换为 Proxy proxy ,然后可以在client.SetProxy()中使用.

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

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

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

推荐答案

尝试一下:

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

更多推荐

OkHTTPClient代理身份验证如何?

本文发布于:2023-11-03 16:22:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555566.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:身份验证   OkHTTPClient

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!