java - java中rest API的身份验证失败错误

标签 java rest authentication

我正在使用下面的代码来执行一些请求:

    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/

相关文章:

java - 如何在返回 HTTP 代码后通知客户端异常

java - 是否有 EGLImage 的 java 版本可以有效地从 OpenGL 读取像素?

Centos 6.6 上的 Elasticsearch 未找到 Java,所有路径变量均已设置且有效

java - 按分数限制 SOLR 中的结果数量

java - 如何在 IntelliJ IDEA 中调试 RESTful Web 服务的 JUnit 测试类?

c# - 在 MVC 4 中限制未登录用户对 Controller 操作的访问

java - MalformedByteSequenceException 1 字节 UTF-8 序列的无效字节 1

javascript - 在离线优先应用程序的情况下,如何与远程数据库同步数据?

java - 如何通过以编程方式设置用户名和密码来连接到 ActiveMQ 服务器?

ruby-on-rails - Railscasts 的 "Authentication from Scratch"有多安全?