基本上我需要做的是执行摘要身份验证。我尝试的第一件事是可用的官方示例here http://svn.apache.org/repos/asf/httpcomponents/httpclient/tags/4.0.1/httpclient/src/examples/org/apache/http/examples/client/ClientAuthentication.java。
但是当我尝试执行它时(进行一些小的更改,Post 而不是 Get 方法)我得到一个
org.apache.http.auth.MalformedChallengeException: missing nonce in challange
at org.apache.http.impl.auth.DigestScheme.processChallenge(DigestScheme.java:132)
当失败时我尝试使用:
DefaultHttpClient client = new DefaultHttpClient();
client.getCredentialsProvider().setCredentials(new AuthScope(null, -1, null), new UsernamePasswordCredentials("<username>", "<password>"));
HttpPost post = new HttpPost(URI.create("http://<someaddress>"));
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("domain", "<username>"));
post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
DigestScheme digestAuth = new DigestScheme();
digestAuth.overrideParamter("algorithm", "MD5");
digestAuth.overrideParamter("realm", "http://<someaddress>");
digestAuth.overrideParamter("nonce", Long.toString(new Random().nextLong(), 36));
digestAuth.overrideParamter("qop", "auth");
digestAuth.overrideParamter("nc", "0");
digestAuth.overrideParamter("cnonce", DigestScheme.createCnonce());
Header auth = digestAuth.authenticate(new
UsernamePasswordCredentials("<username>", "<password>"), post);
System.out.println(auth.getName());
System.out.println(auth.getValue());
post.setHeader(auth);
HttpResponse ret = client.execute(post);
ByteArrayOutputStream v2 = new ByteArrayOutputStream();
ret.getEntity().writeTo(v2);
System.out.println("----------------------------------------");
System.out.println(v2.toString());
System.out.println("----------------------------------------");
System.out.println(ret.getStatusLine().getReasonPhrase());
System.out.println(ret.getStatusLine().getStatusCode());
起初,我只覆盖了“realm”和“nonce”DigestScheme 参数。但事实证明,在服务器上运行的 PHP 脚本需要所有其他参数,但无论我是否指定它们,当我调用其authenticate() 方法时,DigestScheme 都不会在 Authorization RequestPreperty 中生成它们。 PHP 脚本返回 HTTP 响应代码 200,并显示 PHP 脚本需要 cnonce、nc 和 qop 参数的消息。
我已经为此苦苦挣扎了两天,但没有运气。根据一切,我认为问题的原因是 PHP 脚本。在我看来,当应用程序尝试未经授权访问它时,它不会发出挑战。
有人有什么想法吗?
编辑:
另一件事是,我尝试使用 cURL 连接并且它有效。