You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio(Java)查询Spotify API:消除外部浏览器获取Token的方法

用WebView在App内完成Token获取(消除外部浏览器跳转)

1. 布局中添加WebView

在你的Activity布局文件(比如activity_token_auth.xml)里加入WebView,初始可以设为隐藏状态,需要时再显示:

<WebView
    android:id="@+id/auth_webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="gone" />

2. 配置WebView并处理授权流程

在Java Activity中初始化WebView,核心是通过WebViewClient拦截授权回调URL,直接在App内解析Token,避免跳转外部浏览器:

import android.os.Bundle;
import android.view.View;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.appcompat.app.AppCompatActivity;

public class TokenAuthActivity extends AppCompatActivity {
    private WebView authWebView;
    // 替换成你的授权地址和自定义回调地址
    private static final String AUTH_URL = "https://your-auth-server.com/authorize?client_id=xxx&redirect_uri=your-app-callback://token&response_type=token";
    private static final String CALLBACK_SCHEME = "your-app-callback://token";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_token_auth);

        authWebView = findViewById(R.id.auth_webview);
        initWebViewConfig();
        // 显示WebView并加载授权页面
        authWebView.setVisibility(View.VISIBLE);
        authWebView.loadUrl(AUTH_URL);
    }

    private void initWebViewConfig() {
        WebSettings webSettings = authWebView.getSettings();
        // 启用JavaScript,多数授权页面依赖JS交互
        webSettings.setJavaScriptEnabled(true);
        // 开启DOM存储,保存授权会话数据
        webSettings.setDomStorageEnabled(true);
        // 禁用缩放优化体验
        webSettings.setSupportZoom(false);
        webSettings.setBuiltInZoomControls(false);

        // 拦截URL跳转,核心逻辑
        authWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                String url = request.getUrl().toString();
                // 检测是否触发了我们的回调地址
                if (url.startsWith(CALLBACK_SCHEME)) {
                    // 从URL中提取Token
                    String token = extractToken(url);
                    if (token != null) {
                        // 处理获取到的Token,比如存到本地缓存
                        processToken(token);
                        // 隐藏WebView
                        authWebView.setVisibility(View.GONE);
                        // 可选:结束当前授权页面
                        finish();
                    }
                    return true; // 拦截该跳转,不再继续加载
                }
                // 其他授权相关页面继续在WebView内加载
                return super.shouldOverrideUrlLoading(view, request);
            }
        });
    }

    // 解析回调URL中的access_token
    private String extractToken(String url) {
        if (url.contains("access_token=")) {
            String[] splitParts = url.split("access_token=");
            StringTokenSegment = splitParts[1];
            // 截断后续其他参数
            if (tokenSegment.contains("&")) {
                tokenSegment = tokenSegment.split("&")[0];
            }
            return tokenSegment;
        }
        return null;
    }

    private void processToken(String token) {
        // 这里写你的Token处理逻辑,比如保存到SharedPreferences
        // SharedPreferences sp = getSharedPreferences("AppConfigs", MODE_PRIVATE);
        // sp.edit().putString("AUTH_TOKEN", token).apply();
    }

    // 销毁WebView避免内存泄漏
    @Override
    protected void onDestroy() {
        if (authWebView != null) {
            authWebView.removeAllViews();
            authWebView.destroy();
            authWebView = null;
        }
        super.onDestroy();
    }
}

3. 添加必要权限

在AndroidManifest.xml中添加网络权限:

<uses-permission android:name="android.permission.INTERNET" />

关键注意事项

  • 提前在你的授权服务器后台,把自定义的redirect_uri(即your-app-callback://token)加入允许的回调地址列表,否则授权会失败。
  • 如果授权页面有HTTPS证书校验问题,调试阶段可以临时添加证书信任逻辑,但正式环境必须使用合法证书。
  • 可以把WebView封装成Dialog或Fragment,不用单独开Activity,体验更流畅。

内容的提问来源于stack exchange,提问作者Mason Miller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 16:05:10