[英]Get django OAuth2 Toolkit access token from android client
拜托,你能幫我嗎?我怎樣才能從android客戶端獲取django OAuth2 Toolkit訪問令牌,就像我們用curl一樣? 我好幾天嘗試了許多方法都是徒勞的。 對於其他信息,我使用retrofit作為android http庫。
從django Oauth2工具包獲取Android應用程序上的令牌有不同的選項,例如,您可以:
在這里,您有關於如何將應用程序注冊為URL方案的處理程序的說明,這將允許您從瀏覽器返回到您的應用程序:
http://appurl.org/docs/android
(同樣在最后一個鏈接中,您可以在幻燈片編號20中看到另一個示例)
此問題解釋了如何將數據從瀏覽器重定向並傳遞到手機:
在這里你有Oauth和Android之間的工作流程:
它從第十五張幻燈片開始。
另一個選項可以是將您的應用程序定義為授權類型密碼,並執行請求令牌的請求:
HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(LOGIN_API); // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("username", USERNAME)); nameValuePairs.add(new BasicNameValuePair("password", PASSWORD)); nameValuePairs.add(new BasicNameValuePair("grant_type", "password")); nameValuePairs.add(new BasicNameValuePair("client_id", CLIENT ID)) nameValuePairs.add(new BasicNameValuePair("client_secrect", CLIENT SECRET)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost);
使用方法取決於您的應用程序的用例。
社區編輯:
HttpClient在過去幾年中已被棄用。 這是替代代碼:
String data = URLEncoder.encode( "grant_type", "UTF-8" ) + "=" + URLEncoder.encode( "password", "UTF-8" );
data += "&" + URLEncoder.encode( "username", "UTF-8" ) + "=" + URLEncoder.encode( USERNAME, "UTF-8" );
data += "&" + URLEncoder.encode( "password", "UTF-8" ) + "=" + URLEncoder.encode( PASSWORD, "UTF-8" );
data += "&" + URLEncoder.encode( "client_id", "UTF-8" ) + "=" + URLEncoder.encode( CLIENT_ID, "UTF-8" );
data += "&" + URLEncoder.encode( "client_secret", "UTF-8" ) + "=" + URLEncoder.encode( CLIENT_SECRET, "UTF-8" );
URL server = new URL( param.url );
HttpURLConnection connection = ( HttpURLConnection ) server.openConnection();
connection.setDoOutput( true );
OutputStreamWriter osw = new OutputStreamWriter( connection.getOutputStream() );
osw.write( data );
osw.flush();
int responseCode = connection.getResponseCode();
if( responseCode == HttpStatus.SC_OK )
{
BufferedReader reader = new BufferedReader( new InputStreamReader( connection.getInputStream() ) );
StringBuffer response = new StringBuffer();
String line = "";
while( ( line = reader.readLine() ) != null )
{
response.append( line );
}
Log.v( "Login", response.toString() );
}
else
{
Log.v( "CatalogClient", "Response code:" + responseCode );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.