我正在使用下面的代码来执行一些请求:
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("testrail.xyz.com", 80),
new UsernamePasswordCredentials("abc@xyz.com", "test123"));
try {
// specify the host, protocol, and port
HttpHost target = new HttpHost("testrail.xyz.com", 80, "http");
// specify the get request
HttpGet getRequest = new HttpGet("/index.php?/api/v2/get_runs/52");
getRequest.addHeader("Content-Type", "application/json;charset=UTF-8");
System.out.println("executing request to " + target);
HttpResponse httpResponse = httpclient.execute(target, getRequest);
HttpEntity entity = httpResponse.getEntity();
System.out.println("----------------------------------------");
System.out.println(httpResponse.getStatusLine());
Header[] headers = httpResponse.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
我收到的回复是:
executing request to http://testrail.mypublisher.com:80
----------------------------------------
HTTP/1.1 401 Unauthorized Date: Wed, 04 Nov 2015 17:19:05 GMT Server: Apache X-Powered-By: PHP/5.3.3 Content-Length: 87 Connection: close Content-Type: application/json; charset=utf-8
----------------------------------------
{"error":"Authentication failed: invalid or missing user/password or session cookie."}
我传递了身份验证凭据,但仍然收到此错误。当我手动登录应用程序或通过 Firefox Rest 客户端触发上述请求时,它工作正常。 我哪里出错了? 我正在使用 4.5.1 httpclient jar 文件。
最佳答案
试试这个(来自 Apache HTTPClient 文档):
/**
* A simple example that uses HttpClient to execute an HTTP request against
* a target site that requires user authentication.
*/
public class ClientAuthentication {
public static void main(String[] args) throws Exception {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope("httpbin.org", 80),
new UsernamePasswordCredentials("user", "passwd"));
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.build();
try {
HttpGet httpget = new HttpGet("http://httpbin.org/basic-auth/user/passwd");
System.out.println("Executing request " + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
关于java - java中rest API的身份验证失败错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33528727/