http摘要认证 java,Java客户端程序使用HttpClient API发送摘要身份验证请求

I have restlet sample client program which sends the digest request. Similar to this I need java client program which sends a digest request using HttpClient api.

Can anybody send me sample code. Thanks in advance.

Reference reference = new Reference("http://localhost:8092/authenticate");

Client client = new Client(Protocol.HTTP);

Request request = new Request(Method.GET, reference);

Response response = client.handle(request);

System.out.println("response: "+response.getStatus());

Form form = new Form();

form.add("username", "rajesh");

form.add("uri", reference.getPath());

// Loop over the challengeRequest objects sent by the server.

for (ChallengeRequest challengeRequest : response

.getChallengeRequests()) {

// Get the data from the server's response.

if (ChallengeScheme.HTTP_DIGEST

.equals(challengeRequest.getScheme())) {

Series params = challengeRequest.getParameters();

form.add(params.getFirst("nonce"));

form.add(params.getFirst("realm"));

form.add(params.getFirst("domain"));

form.add(params.getFirst("algorithm"));

form.add(params.getFirst("qop"));

}

}

// Compute the required data

String a1 = Engine.getInstance().toMd5(

"rajesh" + ":" + form.getFirstValue("realm") + ":" + "rajesh");

String a2 = Engine.getInstance().toMd5(

request.getMethod() + ":" + form.getFirstValue("uri"));

form.add("response", Engine.getInstance().toMd5(

a1 + ":" + form.getFirstValue("nonce") + ":" + a2));

ChallengeResponse challengeResponse = new ChallengeResponse(

ChallengeScheme.HTTP_DIGEST, "", "");

challengeResponse.setCredentialComponents(form);

// Send the completed request

request.setChallengeResponse(challengeResponse);

response = client.handle(request);

// Should be 200.

System.out.println(response.getStatus());

解决方案

Here you go:

HttpClient client = new HttpClient();

Credentials creds = new UsernamePasswordCredentials(username, password);

client.getState().setCredentials(new AuthScope(host, port, realmName), creds);

GetMethod get = new GetMethod(url);

get.setDoAuthentication(true);

client.getParams().setAuthenticationPreemptive(true); // seems to be necessary in most cases

client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, Collections.singleton(AuthPolicy.DIGEST));//need to register DIGEST scheme not the basic

client.getAuthSchemes().register(AuthPolicy.DIGEST, new DigestSchemeFactory());

client.executeMethod(get);

result = get.getResponseBodyAsString();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值