HttpGet Digest授权认证

工具类: compile ‘com.burgstaller:okhttp-digest:1.13’

import android.content.Context;

import com.burgstaller.okhttp.AuthenticationCacheInterceptor;
import com.burgstaller.okhttp.CachingAuthenticatorDecorator;
import com.burgstaller.okhttp.DispatchingAuthenticator;
import com.burgstaller.okhttp.digest.CachingAuthenticator;
import com.burgstaller.okhttp.digest.Credentials;
import com.burgstaller.okhttp.digest.DigestAuthenticator;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;

public class HttpUtils {
    private Context context;
    private CallBackResponse callback;
    static String resposes;

    public HttpUtils(Context context) {
        this.context = context;
    }

    public void setOnCallback(CallBackResponse callback) {
        this.callback = callback;
    }

    public interface CallBackResponse {
        void onSuccess(String response);
    }

    public void pullNews(String url) {

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        final Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>();

        Credentials credentials = new Credentials("Hsp-2E9D30C1C1914BC7A14E17E257648563",
                "5894D3C2D891473E804A3814E5D61D4B");//授权用户名和密码
        final DigestAuthenticator digestAuthenticator = new DigestAuthenticator(credentials);
        DispatchingAuthenticator authenticator = new DispatchingAuthenticator.Builder().with("digest",
                digestAuthenticator).build();
        okhttp3.Request request = new okhttp3.Request.Builder().url(url).get()
                .header("X-User-Id", "Hsp-2E9D30C1C1914BC7A14E17E257648563")
                .header("X-Google-Ad-Id", "5894D3C2D891473E804A3814E5D61D4B").build();//header
        OkHttpClient client = builder.authenticator(new CachingAuthenticatorDecorator(authenticator, authCache))
                .addInterceptor(new AuthenticationCacheInterceptor(authCache)).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                resposes = response.body().string();
                if (callback != null) {
                    callback.onSuccess(resposes);
                }

            }
        });

    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值