简体   繁体   English

从Apache Http客户端旧版迁移到OkHttp

[英]Migrating from Apache Http client legacy to OkHttp

I'm migrating some code from the Apache HTTP client to OkHttp as the Apache client was deprecated in API 23 and now, in API 29 totally eliminated. 我正在将一些代码从Apache HTTP客户端迁移到OkHttp,因为Apache客户端已在API 23中弃用,而现在在API 29中已完全淘汰。 In general I'm not having too many problems but there's a line for which I can't find an equivalent: 总的来说,我并没有太多的问题,但是我找不到对应的一行:

myHttpPost.addHeader(new BasicScheme().authenticate(
                    new UsernamePasswordCredentials(myUser, myPassword), HttpPost));

I've debugged this line and it generates a String similar to this one: 我调试了这一行,它生成了一个类似于此字符串:

Authorization: Basic RU5YRU5EUkEASDASDQWEQFASkLTk2ZjgtOTASDQWEkMWNkYTA1 授权:基本RU5YRU5EUkEASDASDQWEQFASkLTk2ZjgtOTASDQWEkMWNkYTA1

Reading about it in the documentation I can see that the authenticate method: 在文档中阅读它我可以看到authenticate方法:

Produces an authorization string for the given set of Credentials 为给定的凭据集生成授权字符串

And that the UsernamePasswordCredentials basically creates that credentials from my user and password but I can't find the equivalent in OkHttp, anyone has faced this problem? 而且UsernamePasswordCredentials基本上是根据我的用户名和密码创建该凭据的,但是我在OkHttp中找不到等效的凭据,有人遇到过这个问题吗?

I have managed to find a class in the OkHttp docs , an Authenticator , but I'm not really sure it's what I'm looking for. 我已经设法在OkHttp docs中找到一个类Authenticator ,但是我不太确定这是我要找的东西。

You're looking for Credentials.basic() . 您正在寻找Credentials.basic()

        String credential = Credentials.basic("jesse", "password1");
        return Request.Builder()
            .header("Authorization", credential)
            ...
            .build();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM