AFOAuth2Client相当于Java

时间:2013-11-25 20:40:22

标签: java android rest oauth

我需要使用用户名和密码对oauth提供商进行授权。在iOS方面,有开源库&AFOAuth2Client'这很好用。有图书馆吗?或者我将如何使用Java代码?我试过这个:

this.http_client = new DefaultHttpClient();

    oauth_consumer = new CommonsHttpOAuthConsumer(Constants.clientId, Constants.clientSecret);

    HttpPost httppost = new HttpPost("https://test.com/v1/oauth/token?api_key=gnxkfzquuahaswuxjrkv9ct3");
    ArrayList<BasicNameValuePair> name_value_pairs = new ArrayList<BasicNameValuePair>(2);
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("grant_type", "password");

    params.put("username", "xxxxx@everything.com");
    params.put("password", "xxxxx");
    Iterator iter = params.entrySet().iterator();
    while (iter.hasNext())
    {
        Map.Entry pairs = (Map.Entry) iter.next();
        name_value_pairs.add(new BasicNameValuePair((String) pairs.getKey(), (String) pairs.getValue()));
    }

    try
    {
        // Put our parameters in our Post
        httppost.setEntity(new UrlEncodedFormEntity(name_value_pairs));

        // sign our request
        this.oauth_consumer.sign(httppost);
        // Yoiks, and away!
        HttpResponse response = http_client.execute(httppost);

        HttpEntity entity = response.getEntity();

        if (entity != null)
        {
            InputStream instream = entity.getContent();
            StringWriter writer = new StringWriter();
            IOUtils.copy(instream, writer);
            String theString = writer.toString();
            JSONObject json = new JSONObject(theString);
            // Closing the input stream will trigger connection release
            instream.close();
            return json;
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

谢谢,Graeme

1 个答案:

答案 0 :(得分:2)

我结束了,因为我有同样的问题。我最终做了以下事情:

找出用户对应用程序的期望。在我的情况下,它是以下(因为你使用AFOAuth2Client库,我认为它也是你的。

包含以下参数的GET请求:"URL_TO_YOUR_SERVER"?client_id=YOURCLIENTID&client_secret=YOURCLIENTESECRET&username=YOURUSERNAME&password=YOURPASSWORD&grant_type=password

是的,“grant_type”的值是登录时的密码(这意味着您将收到您的身份验证令牌以及刷新令牌)。无论响应如何,您都需要先了解。在我的例子中,它是以JSON格式发回的数据。我会发布随后执行此操作的代码:

以下方法只是使用我提到的GET参数构造url。

private String getSignInURL(UserAccount accountValues){
    List<NameValuePair> params = new LinkedList<NameValuePair>();
    params.add(new BasicNameValuePair("client_id", accountValues.getClient_id() ));
    params.add(new BasicNameValuePair("client_secret",accountValues.getClient_secret() ));
    params.add(new BasicNameValuePair("grant_type", "password"));
    params.add(new BasicNameValuePair("username", accountValues.getEmail() ));
    params.add(new BasicNameValuePair("password", accountValues.getPassword() ));

    String paramString = URLEncodedUtils.format(params, "utf-8");

    return this.baseUrl+"?"+paramString;
}

以下方法进行GET调用。

public AuthTokens userSignIn(UserAccount accountValues)
        throws Exception {

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(this.getSignInURL(accountValues));

    AuthTokens authTokens = null; 

    try {
        HttpResponse response = httpClient.execute(httpGet);

        if (response.getStatusLine().getStatusCode() != 200) {
            reportException(response);
        } 

        authTokens = getAuthTokensFromJson( getJsonFormat(response.getEntity().getContent()) ); 
    } catch (Exception e) {
        e.printStackTrace();
    } 

  return authTokens;
}

以下内容使得String允许您创建JSON对象response.getEntity().getContent()

protected String getJsonFormat(InputStream inputStream) throws IOException{
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
    StringBuilder sb = new StringBuilder();

    String line = null;
    while ((line = reader.readLine()) != null)
    {
        sb.append(line + "\n");
    }

    return sb.toString();
}

最后,这是从服务器响应中读取authTokens的方法。

private AuthTokens getAuthTokensFromJson(String toJson) throws IOException, JSONException {
    AuthTokens authTokens = new AuthTokens();

    JSONObject jObject = new JSONObject(toJson);
    authTokens.setAuthToken(jObject.getString("access_token"));
    authTokens.setRefreshToken(jObject.getString("refresh_token"));

    return authTokens;
}

这就是全部,希望它有所帮助。