在Java中使用HttpClient的HTTP基本身份验证?

在Java中使用HttpClient的HTTP基本身份验证?

我试图在Java中模仿这个curl命令的功能:

curl --basic --user username:password -d "" http://ipaddress/test/login

我使用CommonsHttpClient3.0编写了以下代码,但最终得到了500 Internal Server Error从服务器。有人能告诉我做错什么了吗?

public class HttpBasicAuth {

    private static final String ENCODING = "UTF-8";

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {

            HttpClient client = new HttpClient();

            client.getState().setCredentials(
                    new AuthScope("ipaddress", 443, "realm"),
                    new UsernamePasswordCredentials("test1", "test1")
                    );

            PostMethod post = new PostMethod(
                    "http://address/test/login");

            post.setDoAuthentication( true );

            try {
                int status = client.executeMethod( post );
                System.out.println(status + "\n" + post.getResponseBodyAsString());
            } finally {
                // release any connection resources used by the method
                post.releaseConnection();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
   }



SMILET
浏览 1637回答 3
3回答

一只名叫tom的猫

您是否尝试过(使用HttpClient版本4):String encoding = Base64Encoder.encode(user + ":" + pwd);HttpPost httpPost = new HttpPost("http://host:post/test/login");httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoding);System.out.println("executing request " + httpPost.getRequestLine());HttpResponse response = httpClient.execute(httpPost);HttpEntity entity = response.getEntity();
打开App,查看更多内容
随时随地看视频慕课网APP