【问题标题】:Equivalent of HTTPBasicAuth (python) in OkHttp (Android)OkHttp (Android) 中 HTTPBasicAuth (python) 的等价物
【发布时间】:2015-11-25 02:37:06
【问题描述】:

我需要在 python 中获取身份验证密钥:auth = requests.auth.HTTPBasicAuth(client_id, client_secret) 代码。如何在 java 中获取它(我使用 OkHttp for Android 应用程序)。

【问题讨论】:

    标签: java android python http okhttp


    【解决方案1】:

    使用 OkHttp,您可以像这样在您的 OkHttpClient 上创建 Authenticator

    OkHttpClient myOkHttpClient = new OkHttpClient();
    myOkHttpClient.setAuthenticator(new Authenticator() {
            @Override
            public Request authenticate(Proxy proxy, Response response) throws IOException {
                String credential = Credentials.basic("Username", "Password");
                return response.request().newBuilder().header("Authorization", credential).build();
            }
    
            @Override
            public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                return null;
            }
        });
    

    这应该可以完成工作。我发现没有太多关于使用基本身份验证的文档,但我从以下位置找到了一些帮助:Android OkHttp with Basic Authentication

    【讨论】:

    • 方法验证在服务器返回 401 错误时有效。最好的方法是在拦截器的 Header 中设置凭据。
    猜你喜欢
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    • 2013-02-06
    • 2012-03-22
    • 2016-12-27
    • 2013-12-13
    相关资源
    最近更新 更多