java - 如何使用 apache httpClient 设置基本身份验证

标签 java apache-httpclient-4.x apache-commons-httpclient

我正在尝试使用 Apache httpclient 执行 PATCH 请求,但我不确定如何设置基本身份验证。这就是我目前正在尝试做的事情。我知道我的身份验证参数是正确的,我可以使用 GET 进行身份验证...但对于 GET 我当前使用 httpURLConnection 而不是 Apache httpClient 。

使用此代码,我收到了 403 响应,我相信这是因为我没有正确设置身份验证信息。我知道我只需要进行基本身份验证并为其提供 X_AUTH_USER、X_AUTH_CRED。

Authenticator.setDefault(new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(X_AUTH_USER, X_AUTH_CRED.toCharArray());
        }
    });

    HttpClient client = HttpClientBuilder.create().build();
    HttpPatch patch = new HttpPatch(buildUrl());


    try {
        StringEntity input = new StringEntity(buildJson(jsonList));
        input.setContentType("application/json");
        patch.setEntity(input);

        System.out.println(patch);

        HttpResponse response = client.execute(patch);

        System.out.print(response.getStatusLine());
        for(Header header : response.getAllHeaders()){
            System.out.println(header.getName() + " : " + header.getValue());
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

最佳答案

更新:

Authenticator.setDefault(new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("UserName", "P@sw0rd".toCharArray());
    }
});

您还需要设置其他 header 属性:(示例)

response.addHeader("Access-Control-Allow-Methods", "");
response.setHeader("Access-Control-Allow-Origin", "http://podcastpedia.org");
//allows CORS requests only coming from podcastpedia.org

向 httpURLConnection 添加基本身份验证属性的代码

String basic = "Basic " + Base64.encodeToString(("admin:1234").getBytes(), Base64.NO_WRAP);

con.setRequestProperty("Authorization", basic);

关于java - 如何使用 apache httpClient 设置基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27464210/

相关文章:

java - 获取已经随机生成矩阵的整数

java - 当响应始终正确关闭时如何重构代码?

java - 使用 Apache HttpClient 如何在请求和响应中设置 TIMEOUT

java - 循环中的 HttpClient

java - 从一个列表中选择另一个列表中的值 HQL

java - 我怎样才能像这样从数据库获取数据到jtable

java - 如何使用 ReadableByteChannel 获取文件内容并将其存储在 byteBuffer 中?

Java 的 XML DocumentBuilder 因解析超时而失败?

java - 如何让 HttpClient 返回状态码和响应正文?

java - 如何处理/读取 "Transfer-Encoding:chunked"的响应?