如何解决OAuth 2.0 使用 Android 应用程序访问 Foursquare API
我正在尝试实施 OAuth 2.0 以访问我的 Android 应用程序上的 Foursquare API。使用 OAuth 2.0,我试图让我的用户注册和/或登录 Foursquare 并授予我的应用程序获取令牌的权限。
这是我迄今为止尝试过的方法,但似乎不起作用。有人可以帮我找出我的方法的问题吗?任何指针将不胜感激。非常感谢您的帮助!
我的主要活动:
package com.example.testingoauth;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
private static final String CLIENT_ID = "myClientID";
private static final String CLIENT_SECRET = "myClientSecret";
private static final String YOUR_REGISTERED_REDIRECT_URI = "oauth-android-app://test";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonLogin;
buttonLogin = findViewById(R.id.btnLogin);
buttonLogin.setonClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loginToFoursquare();
}
});
}
private void loginToFoursquare() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(
Uri.parse(
"https://foursquare.com/oauth2/authenticate" +
"?client_id=" + CLIENT_ID +
"&response_type=code" +
"&redirect_uri=" + YOUR_REGISTERED_REDIRECT_URI
)
);
startActivity(intent);
}
public void onResume() {
super.onResume();
Uri uri = this.getIntent().getData();
if (uri != null) {
String code = null;
if ((code = uri.getQueryParameter("code")) != null) {
new gettingToken().execute(code);
}
}
}
private class gettingToken extends AsyncTask<String,String,String> {
@Override
protected String doInBackground(String... params) {
try {
JSONObject tokenjson = executeHttpGet(
"https://foursquare.com/oauth2/access_token" +
"?client_id=" + CLIENT_ID +
"&client_secret=" + CLIENT_SECRET +
"&grant_type=authorization_code" +
"&redirect_uri=" + YOUR_REGISTERED_REDIRECT_URI +
"&code=" + params[0]
);
String token = tokenjson.getString("access_token");
JSONObject userjson = executeHttpGet(
"https://api.foursquare.com/v2/" +
"users/self/" +
"checkins" +
"?oauth_token=" + token +
"&v=20210701"
);
int returnCode = Integer.parseInt(userjson.getJSONObject("Meta").getString("code"));
if (returnCode == 200) {
Log.i("LoginTest",userjson.getJSONObject("response").getJSONObject("user").toString());
}else {
Log.e("LoginTest","Wrong return code: " + params[0]);
}
} catch (Exception e) {
Log.e("LoginTest","Login to Foursquare Failed");
}
return null;
}
}
private static JSONObject executeHttpGet(String uri) throws Exception{
HttpGet req = new HttpGet(uri);
HttpClient client = new DefaultHttpClient();
HttpResponse resLogin = client.execute(req);
BufferedReader r = new BufferedReader(new InputStreamReader(resLogin.getEntity().getContent()));
StringBuilder sb = new StringBuilder();
String s = null;
while ((s = r.readLine()) != null) {
sb.append(s);
}
return new JSONObject(sb.toString());
}
}
我的 AndroidManifest.xml:(我为方案添加了意图过滤器)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testingoauth">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.TestingOAuth">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.broWSABLE" />
<data android:scheme="oauth-android-app" />
</intent-filter>
</activity>
</application>
</manifest>
我的 build.gradle:(除了我添加了 apache 库,我没有更改 Empty Activity 默认设置的任何内容)
plugins {
id 'com.android.application'
}
android {
compileSdkVersion 30
buildToolsversion "30.0.3"
useLibrary 'org.apache.http.legacy'
defaultConfig {
applicationId "com.example.testingoauth"
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。