Java 如何在httpget中设置用户名/密码

Java 如何在httpget中设置用户名/密码,java,httpclient,Java,Httpclient,我使用Apache HttpComponents访问web服务,不知道如何在请求中设置用户/密码,以下是我的代码: URI url = new URI(query); HttpGet httpget = new HttpGet(url); DefaultHttpClient httpclient = new DefaultHttpClient(); Credentials defaultcreds = new UsernamePasswordCredentials("test", "test"

我使用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);

但它还是犯了错误

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]

我不确定设置用户/密码的方法是否正确?有人能帮忙吗?谢谢。

我认为你的思路是对的。也许您应该检查您的用户凭据,因为http可能意味着用户名/密码不正确,或者用户没有访问资源的权限。我有下面的代码,我做基本的http身份验证,它工作得很好

import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;


public class Authentication
{

    public static void main(String[] args)
    {

        DefaultHttpClient dhttpclient = new DefaultHttpClient();

        String username = "abc";
        String password = "def";
        String host = "abc.example.com";
        String uri = "http://abc.example.com/protected";

        try
        {
            dhttpclient.getCredentialsProvider().setCredentials(new AuthScope(host, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password));
            HttpGet dhttpget = new HttpGet(uri);

            System.out.println("executing request " + dhttpget.getRequestLine());
            HttpResponse dresponse = dhttpclient.execute(dhttpget);

            System.out.println(dresponse.getStatusLine()    );
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            dhttpclient.getConnectionManager().shutdown();
        }

    }

}