我使用 Apache HttpComponents 访问 Web 服务,但不知道如何在请求中设置用户/密码,这是我的代码:
URI url = new URI(query);
HttpGet httpget = new HttpGet(url);
DefaultHttpClient httpclient = new DefaultHttpClient();
Credentials defaultcreds = new UsernamePasswordCredentials("test", "test");
httpclient.getCredentialsProvider().setCredentials(new AuthScope(HOST, AuthScope.ANY_PORT), defaultcreds);
HttpResponse response = httpclient.execute(httpget);
..
但它仍然得到 401 未经授权的错误。
HTTP/1.1 401 Unauthorized [Server: Apache-Coyote/1.1, Pragma: No-cache, Cache-Control: no-cache, Expires: Wed, 31 Dec 1969 16:00:00 PST, WWW-Authenticate: Basic realm="MemoryRealm", Content-Type: text/html;charset=utf-8, Content-Length: 954, Date: Wed, 04 Apr 2012 02:28:49 GMT]
我不确定它是否设置用户/密码的正确方法?有人可以帮忙吗?谢谢。