java - Java 中的 AFOAuth2Client 等价物

标签 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();
    }

谢谢,格雷姆

最佳答案

我最终来到这里是因为我遇到了同样的问题。我最终做了以下事情:

找出用户对应用程序的确切期望。在我的例子中,它是以下内容(我认为它也是你的,因为你正在使用 AFOAuth2Client 库。

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

是的,“grant_type”的值是登录时的密码(这意味着您将收到您的授权 token 和刷新 token )。无论回应是什么,您都需要先找出答案。在我的例子中,它是以 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;
}

下面生成允许您创建 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;
}

就这些了,希望对大家有帮助。

关于java - Java 中的 AFOAuth2Client 等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20202844/

相关文章:

java - 估计/拟合数据到 Android 中的 exGaussian 分布

java - 只有带控件的数字

java - Bing 文本转语音功能在 Android 中不工作

rest - 来自 org.apache.hadoop.hbase.client.HConnectionManager.createConnection 的 InvocationTargetException 异常

java - Java 中用于唯一 ID 的序列生成器

java - 由于类型无效,无法 hibernate @ManyToMany

java - 如何在 Android 中更改 Spinner 选择的背景颜色

android - relativelayout采用全屏,layout_height为="80dp"

json - 将 Outlook REST API 项目 ID 转换为 MAPI EntryID

angularjs - 现代 Web 应用程序中的 'API first architecture' 是什么