我正在尝试使用 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/