【问题标题】:AFOAuth2Client equivalent in JavaJava 中的 AFOAuth2Client 等效项
【发布时间】:2013-12-10 18:08:32
【问题描述】:

我需要使用用户名和密码对 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();
    }

谢谢,格雷姆

【问题讨论】:

    标签: java android rest oauth


    【解决方案1】:

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

    找出用户对应用程序的期望究竟是什么。就我而言,它是以下内容(我认为它也是您的,因为您使用的是 AFOAuth2Client 库。

    带有以下参数的 GET 请求:"URL_TO_YOUR_SERVER"?client_id=YOURCLIENTID&amp;client_secret=YOURCLIENTESECRET&amp;username=YOURUSERNAME&amp;password=YOURPASSWORD&amp;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;
    }
    

    下面的字符串可以让你创建一个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;
    }
    

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

    【讨论】:

    • 我使用了这种方法,但不得不切换到HttpPost而不是HttpGet。谢谢你的例子,乔伊。
    • 我很高兴能帮上忙 :)
    猜你喜欢
    • 2011-01-10
    • 2010-09-12
    • 2014-10-16
    • 1970-01-01
    • 2012-11-03
    • 2012-12-15
    • 1970-01-01
    • 2010-10-15
    • 2010-09-22
    相关资源
    最近更新 更多