Java中的AFOAuth2Client等价物
我需要使用用户名和密码对oauth提供程序进行授权。在iOS端,有一个开源库“AFOAuth2Client”,运行良好。有图书馆吗?或者我在Java代码中该怎么做?我试过这个:Java中的AFOAuth2Client等价物,java,android,rest,oauth,Java,Android,Rest,Oauth,我需要使用用户名和密码对oauth提供程序进行授权。在iOS端,有一个开源库“AFOAuth2Client”,运行良好。有图书馆吗?或者我在Java代码中该怎么做?我试过这个: this.http_client = new DefaultHttpClient(); oauth_consumer = new CommonsHttpOAuthConsumer(Constants.clientId, Constants.clientSecret); HttpPost httppos
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();
}
this.http_client=new DefaultHttpClient();
oauth_consumer=新的CommonHttpOAuthConsumer(Constants.clientId,Constants.clientSecret);
HttpPost HttpPost=新的HttpPost(“https://test.com/v1/oauth/token?api_key=gnxkfzquuahaswuxjrkv9ct3");
ArrayList name\u value\u pairs=新的ArrayList(2);
HashMap params=新的HashMap();
参数put(“授权类型”、“密码”);
参数put(“用户名”xxxxx@everything.com");
参数put(“密码”、“xxxxx”);
迭代器iter=params.entrySet().Iterator();
while(iter.hasNext())
{
Map.Entry pairs=(Map.Entry)iter.next();
name_value_pairs.add(新的BasicNameValuePairs((字符串)pairs.getKey(),(字符串)pairs.getValue());
}
尝试
{
//把我们的参数放在我们的帖子里
setEntity(新的UrlEncodedFormEntity(名称\值\对));
//签署我们的请求
此.oauth_消费者号(httppost);
//哎呀,走开!
HttpResponse response=http_client.execute(httppost);
HttpEntity=response.getEntity();
如果(实体!=null)
{
InputStream instream=entity.getContent();
StringWriter编写器=新的StringWriter();
IOUtils.副本(流内、编写器);
字符串theString=writer.toString();
JSONObject json=新的JSONObject(字符串);
//关闭输入流将触发连接释放
流内关闭();
返回json;
}
}
捕获(例外e)
{
e、 printStackTrace();
}
谢谢,格雷姆,我来这里是因为我有同样的问题。我最后做了以下几件事: 找出用户对应用程序的确切期望。在我的例子中,它如下(我想它也是你的,因为你正在使用AFOAuth2Client库) 具有以下参数的GET请求:
“URL\u到\u您的\u服务器”?客户端\u id=YOURCLIENTID&client\u secret=YourClientSecret&username=YOURUSERNAME&password=YOURPASSWORD&grant\u 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;
}
下面是允许您创建JSON对象的字符串response.getEntity().getContent()
最后,这里是从服务器响应中读取AuthToken的方法
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
。谢谢你的例子,乔伊。我很高兴能帮上忙:)
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();
}
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;
}