【问题标题】:Unable to authorize in API Basic Authentication in Java无法在 Java 中的 API 基本身份验证中授权
【发布时间】:2015-10-07 23:38:43
【问题描述】:

我正在尝试使用 Java 中的 Lithium Social Web API 进行授权。我对 Java 比较陌生,但我觉得我应该工作。我正在使用 webTarget 和 Invocation 构建器尝试通过标头传递授权,但不断获得未经授权的响应。

我已通过下面的 AuthenticationClass 将身份验证更改为 Base64 编码,并且可以使用 API 通过 hurl.it 进行身份验证,并且可以取回数据,因此用户凭据是正确的。我附上了删除用户名和密码的代码示例。如果有人有任何想法,我将不胜感激。

this.webTarget = this.client.target("https://socialweb-analytics.lcloud.com");

    WebTarget webTargetSessionAuthenticate = webTarget.path("/api/public/reports/report/conversation");

    AuthenticationClass newAuth = new AuthenticationClass();
    newAuth.loginValue("USERNAME", "PASSWORD");
    loginValue = newAuth.encodeLogin();

    Object [] starttimeParamObjects = {new String("1438351200000")};
    Object [] reportformatParamObjects = {new String("csv")};
    Object [] endtimeParamObjects = {new String("1439128800000")};
    Object [] companykeyParamObjects = {new String("XXX")};

    System.out.println(loginValue);

     WebTarget webTargetSessionAuthenticateWithQueryParams = webTargetSessionAuthenticate
             .queryParam("startTime", starttimeParamObjects)
             .queryParam("endTime", endtimeParamObjects)
             .queryParam("reportFormat", reportformatParamObjects)
             .queryParam("companyKey", companykeyParamObjects);     

     System.out.println(webTargetSessionAuthenticateWithQueryParams);

     Invocation.Builder invocationBuilderAuth =
                webTargetSessionAuthenticateWithQueryParams.request();
     invocationBuilderAuth.header(HttpHeaders.AUTHORIZATION, "Basic " + loginValue);


     Response response = invocationBuilderAuth.get();//Entity.entity("", MediaType.TEXT_PLAIN_TYPE));
     int responseStatus = response.getStatus();
     System.out.println(responseStatus);

    System.out.println(response.readEntity(String.class));

【问题讨论】:

    标签: java api


    【解决方案1】:

    标题字符串“基本”和“编码登录值”之间需要一个空格。所以尝试改变这一点

     invocationBuilderAuth.header(HttpHeaders.AUTHORIZATION, "Basic" + loginValue);
    

     invocationBuilderAuth.header(HttpHeaders.AUTHORIZATION, "Basic " + loginValue);
    

    【讨论】:

    • 然后检查一下线路上发生了什么
    • 抱歉什么意思?
    • @JordanMacey-Smith 确保您的基本身份验证字符串是好的。然后使用网络分析器检查它在 HTTP 标头中是否正常运行。
    【解决方案2】:

    开箱即用,HttpClient 不进行抢先式身份验证。如果您完全卡住了,您可以尝试使用 AuthCache 和 BasicScheme(不与默认的基本身份验证一起使用)对称为 "preemptive auth" 的基本身份验证进行变体。

    【讨论】:

      猜你喜欢
      • 2012-10-02
      • 1970-01-01
      • 1970-01-01
      • 2015-05-05
      • 1970-01-01
      • 2014-02-10
      • 1970-01-01
      • 2018-07-14
      • 1970-01-01
      相关资源
      最近更新 更多