【发布时间】: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();
}
谢谢,格雷姆
【问题讨论】: