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

            }
        });

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用HttpClient获取Digest认证时,需要进行以下步骤: 1. 创建HttpClient实例 ``` HttpClient httpClient = new DefaultHttpClient(); ``` 2. 创建HttpGet请求 ``` HttpGet httpGet = new HttpGet(url); ``` 3. 执行请求并获取响应 ``` HttpResponse response = httpClient.execute(httpGet); ``` 4. 获取响应状态码 ``` int statusCode = response.getStatusLine().getStatusCode(); ``` 5. 判断状态码是否为401 ``` if (statusCode == HttpStatus.SC_UNAUTHORIZED) { // 获取认证头信息 Header header = response.getFirstHeader("WWW-Authenticate"); if (header != null && header.getValue().startsWith("Digest")) { // 解析认证头信息 DigestScheme digestScheme = new DigestScheme(); digestScheme.processChallenge(header); // 构造Digest认证对象 UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort(), digestScheme.getRealm(), AuthSchemes.DIGEST); HttpClientContext context = HttpClientContext.create(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(authScope, credentials); context.setCredentialsProvider(credentialsProvider); // 重新执行请求 response = httpClient.execute(httpGet, context); } } ``` 6. 获取响应内容 ``` HttpEntity entity = response.getEntity(); String content = EntityUtils.toString(entity); ``` 完整代码示例: ``` public static void main(String[] args) throws Exception { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://www.example.com"); HttpResponse response = httpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_UNAUTHORIZED) { Header header = response.getFirstHeader("WWW-Authenticate"); if (header != null && header.getValue().startsWith("Digest")) { DigestScheme digestScheme = new DigestScheme(); digestScheme.processChallenge(header); String username = "your-username"; String password = "your-password"; UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); HttpHost targetHost = new HttpHost(httpGet.getURI().getHost(), httpGet.getURI().getPort(), httpGet.getURI().getScheme()); AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort(), digestScheme.getRealm(), AuthSchemes.DIGEST); HttpClientContext context = HttpClientContext.create(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(authScope, credentials); context.setCredentialsProvider(credentialsProvider); response = httpClient.execute(httpGet, context); } } HttpEntity entity = response.getEntity(); String content = EntityUtils.toString(entity); System.out.println(content); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值