【问题标题】:Google authentication with Java apache http tokens使用 Java apache http 令牌进行 Google 身份验证
【发布时间】:2012-03-10 13:21:30
【问题描述】:

我正在尝试使用一个简单的 Java 程序向 Google 进行身份验证。我使用我的凭据发布到正确的 URL。我收到带有 HTTP 状态代码 200 的响应,但其中不包含我为用户检索提要所需的任何身份验证令牌。这是代码

private static String postData = "https://www.google.com/accounts/ClientLogin?Content-type=application/x-www-form-urlencoded&accountType=GOOGLE&Email=xxxxxxxx&Passwd=xxxxx";

public GoogleConnector(){
    HttpClient client=new DefaultHttpClient();
    HttpPost method=new HttpPost(postData);
    try{
        HttpResponse response=client.execute(method);
        System.out.println(response.toString());
    }
    catch(Exception e){ 
    }

【问题讨论】:

  • 这是您发布代码示例时的拼写错误,还是在 Content- 和 URL 的其余部分之间真的有两个空格?
  • 对不起,这只是一个错字。

标签: java http token authentication


【解决方案1】:

好的,您遇到的第一个问题是“Content-Type”必须是标头,而不是请求参数。其次,POST 参数应该附加到请求正文,而不是请求 URL。您的代码应如下所示:

HttpClient client = new DefaultHttpClient();

HttpPost method = new HttpPost("https://www.google.com/accounts/ClientLogin");
method.setHeader("Content-Type", "application/x-www-form-urlencoded");

List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>(4);
postParams.add(new BasicNameValuePair("accountType", "GOOGLE"));
postParams.add(new BasicNameValuePair("Email", "xxxxxxx"));
postParams.add(new BasicNameValuePair("Passwd", "xxxxxx"));
postParams.add(new BasicNameValuePair("service", "cl"));

UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParams);
method.setEntity(formEntity);

HttpResponse response=client.execute(method);
System.out.println(response.toString());

【讨论】:

  • 它可以工作,但我仍然没有在响应中得到 SID、LSID 和 Auth cookie。我确实得到了状态 200,这意味着它应该经过身份验证,但我没有得到令牌
  • 当我在 REST 客户端中发布此请求时,我会在响应正文中获得 SID 和 LSID,而不是标题。
  • 很好用,谢谢。但是根据我的阅读,不应使用 SID 和 LSID,而应使用 Auth 令牌。问题是,我在响应正文中找不到 Auth 令牌。对此有什么想法吗?
  • 看起来您还需要指定service 参数才能取回Auth 令牌。
  • 是的,没错,完美:)) 非常感谢。只是一个简短的说明,对于其他来阅读这篇文章的人来说,参数是“Passwd”而不是“Password”,所以你可能想编辑它以避免混淆。
猜你喜欢
  • 2016-05-19
  • 1970-01-01
  • 2017-06-30
  • 2017-04-11
  • 1970-01-01
  • 1970-01-01
  • 2017-02-17
  • 2011-11-13
  • 2014-09-26
相关资源
最近更新 更多