在HttpClient 4.3.x中更正基本身份验证

时间:2015-01-16 11:40:25

标签: java authentication httpclient

我目前使用以下基本身份验证实现:

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(uri);

        // Set the basic authentication
        httpGet.addHeader(BasicScheme.authenticate(
                new UsernamePasswordCredentials("user", "pass"),
                "UTF-8", false));

        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity entity = httpResponse.getEntity();
        ...

代码工作正常但不推荐使用BasicScheme.authenticate

在HttpClient 4.3.x中为请求实现基本身份验证的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

以下适用于我 -

    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpGet httpGet = new HttpGet(uri);

    // Set the basic authentication
    String encoding = Base64Encoder.encode("user:pass");
    httpGet.setHeader("Authorization", "Basic" + encoding);

    HttpResponse httpResponse = httpClient.execute(httpGet);
    HttpEntity entity = httpResponse.getEntity();

请告诉我它是否适合你。