java - 使用 HttpClient 在 Java 中进行 Http 基本身份验证?

标签 java http apache-commons

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

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

我使用 Commons HttpClient 3.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();
        }
    }
   } 

后来又试了一个 Commons HttpClient 4.0.1 但还是一样的错误:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;


public class HttpBasicAuth {

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

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

        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();

            httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), 
                    new UsernamePasswordCredentials("test1", "test1"));

            HttpPost httppost = new HttpPost("http://host:post/test/login");

            System.out.println("executing request " + httppost.getRequestLine());
            HttpResponse response;
            response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            if (entity != null) {
                entity.consumeContent();
            }

            httpclient.getConnectionManager().shutdown();  
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}

最佳答案

您是否尝试过(使用 HttpClient 版本 4):

String encoding = Base64.getEncoder().encodeToString((user + ":" + pwd).getBytes());
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();

关于java - 使用 HttpClient 在 Java 中进行 Http 基本身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3283234/

相关文章:

Python 请求得到响应 [200] 但表单未填写

node.js - 代理服务器未正确处理 OPTIONS 请求

java - apache commons CommandLine 对象是否可以防止命令行注入(inject)?

java - 在 Java 中检查字符串是否是 ISO 语言的 ISO 国家/地区的更简洁方法

java - 使用 Apache Commons Compress 解压缩 tar 文件

java - Java中类设计的最佳方式: An example

java - Ubuntu 加载 JNI 失败

java - 立即停止线程中的 Runnable

java - 如何在java小程序中翻转卡片

http - 具有自定义用户域的 SSL