【问题标题】:java simple http auth not workingjava简单的http身份验证不起作用
【发布时间】:2013-12-12 02:50:34
【问题描述】:

我希望发出 HTTP POST 请求并使用生成的 auth_token,但 while 循环中的打印语句仅打印 x-dnb-user=myusername&x-dnb-pwd=mypass,而不是打印它从服务器收到的响应。我无法弄清楚我哪里出错了。任何帮助,将不胜感激。响应也是作为字典给出的,并且令牌存在于字典的“授权”键中,在这种情况下我将如何检索令牌?

public void sampleAuth(){
        HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("https://maxcvservices.dnb.com/rest/Authentication");
    try {
      ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
      nameValuePairs.add(new BasicNameValuePair("x-dnb-user","myemail"));
      nameValuePairs.add(new BasicNameValuePair("x-dnb-pwd","mypass"));
      post.setEntity(new UrlEncodedFormEntity(nameValuePairs));


      HttpResponse response = client.execute(post);
      BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
      String line = "";
      while ((line = rd.readLine()) != null) {
        System.out.println(line);
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
    }

提前致谢!

【问题讨论】:

    标签: java rest http-post httpclient


    【解决方案1】:

    我认为您可能缺少 Content-type

    post.setHeader("Content-type", "application/x-www-form-urlencoded");
    

    此外,在您启动 rd.readLine 响应之前,您可能应该检查响应的状态代码。服务器可能已经完全拒绝了您,并且没有可读取的行!

    int code = response.getStatusLine().getStatusCode();
    if ( code == HttpStatus.SC_OK ) {
       // Now go fishing for the auth_token
       // Usually these things are returned as headers
    } else {
       System.out.println( "You've been rejected, pal" );
    }
    

    我需要有关您期望的 auth_token 的更多详细信息,但我的猜测是它位于标题为“auth_key”或其他名称的标题中,因此您可以查找它。

    【讨论】:

    • 嗨,鲍勃,感谢您的回复。我确实收到了 400 代码,这就是为什么我认为没有什么可读的。问题是文档说在 HTTP 标头中传递用户 ID 和密码,但所有文档都指示我将用户 ID 和密码作为 NameValuPairs 传递,这是我遵循的。你认为这可能是问题所在吗?如果是这样,我将如何在发布请求的标头中传递 user_id 和密码?
    • 我不知道,但如果文档说标题给它一个标题。此外,如果他们想要实际的 Http Basic Auth,那是一个拥有自己的标头和全部的规范:en.wikipedia.org/wiki/Basic_access_authentication。如果 HttpClient 对此没有一些抽象,我会感到惊讶。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-12
    相关资源
    最近更新 更多