首页 文章

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

提问于
浏览
0

我正在尝试使用 Apache httpclient 执行 PATCH 请求,我不确定如何设置基本身份验证 . 这就是我目前正在努力做到的 . 我知道我的auth参数是正确的,我可以使用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();
    }

1 回答

  • 1

    Update:

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

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

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

    Code to add a basic authentication property to an httpURLConnection

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

相关问题