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

如何在Android Retrofit的GET/POST请求中通过URL参数实现认证?

我已经在Android项目中基于Retrofit实现了带URL参数形式认证(用户名admin,密码admin)的GET和POST请求,下面是完整的配置与代码实现:

1. 权限配置

首先需要在AndroidManifest.xml中添加网络权限:

<uses-permission android:name="android.permission.INTERNET" />
2. Gradle依赖配置

在模块级的build.gradle中添加以下依赖:

implementation 'com.android.volley:volley:1.1.0'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'com.google.code.gson:gson:2.8.5'
3. Api核心类实现

这个类采用单例模式初始化Retrofit实例,确保全局唯一:

public class Api {
    private static final String BASE_URL="https://your_url";
    private static Api instance;
    private final IApiCall iApiCallInterface;
    private Api() {
        Gson gson = new GsonBuilder().setLenient().create();
        final OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
        Retrofit retrofit = new Retrofit.Builder().client(okHttpClient).baseUrl(BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(gson)).build();
        iApiCallInterface = retrofit.create(IApiCall.class);
    }
    public static Api start() {
        return instance = instance == null ? new Api() : instance;
    }
    public Observable<Example> getSendMoneyCountries() {
        return iApiCallInterface.getCategoryList();
    }
}
4. 接口定义(IApiCall)

这里定义了具体的API请求接口,示例为GET请求:

public interface IApiCall {
    //response in in json array
    @Headers("Content-Type: application/json")
    @GET("/json")
    Observable<Example> getCategoryList();
}
5. MainActivity中调用示例

在Activity中初始化Api实例并发起请求,借助RxJava完成线程调度:

private static Api api;
api = Api.start();
api.getSendMoneyCountries()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribeWith(new DisposableObserver<Example>() {
            @Override
            public void onNext(Example response) {
                //clear array list
                //response store in array list
            }
            @Override
            public void onError(Throwable e) {
                //show toast msg
            }
            @Override
            public void onComplete() {
                //perform db insertion operation seperate thread
                //check for duplicate
            }
        });

内容的提问来源于stack exchange,提问作者Sagar H

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:04:42