简体   繁体   中英

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. 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

Reading about it in the documentation I can see that the authenticate method:

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?

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.

You're looking for Credentials.basic() .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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