如何使用改造 Android 调用具有动态参数的 api?
Posted
技术标签:
【中文标题】如何使用改造 Android 调用具有动态参数的 api?【英文标题】:How to call api with dynamic parameter using retrofit Android? 【发布时间】:2022-01-19 13:56:17 【问题描述】:我正在尝试使用改造库将数据发布到服务器。 Api 包含动态参数个数,如:
https:xyz.com/skill-add?skill[0]=10&skill1=11&skill[2]=12&skill[3]=267
这里是邮递员 SS:
我不知道如何使用像这样的api。
你能帮帮我吗?
【问题讨论】:
【参考方案1】:请在@QueryMap Map
public class ApiClient
static WebApiService webApiService;
public static WebApiService getWebApiService()
if(webApiService == null)
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
try
httpClient.addInterceptor(new Interceptor()
@Override
public Response intercept(Interceptor.Chain chain) throws IOException
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.addHeader("Authorization","Bearer "+getUserAccessToken())
.addHeader("access-token",getUserAccessToken())
.addHeader("device-type", "android")
Request request = requestBuilder.build();
return chain.proceed(request);
);
catch (Exception e)
e.printStackTrace();
OkHttpClient okHttpClient = httpClient.addInterceptor(interceptor).connectTimeout(60, TimeUnit.SECONDS).
readTimeout(60, TimeUnit.SECONDS).
writeTimeout(60, TimeUnit.SECONDS)
.build();
String baseUrl = "https:xyz.com/";//put this in build.gradel and get from build config
Retrofit retrofit = new Retrofit.Builder()
.client(okHttpClient)
.baseUrl(baseUrl)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
webApiService = retrofit.create(WebApiService.class);
return webApiService;
public interface WebApiService
@POST("skill-add")
Observable<Response<ResponseBody>> addskill(@Body Map<String, String> params);
@POST("skill-add")
Observable<Response<ResponseBody>> addskill(@QueryMap Map<String, String> params);
@POST("skill-add")
Observable<Response<ResponseBody>> addskill(@Query("skill[0]") int skill0,@Query("skill[1]") int skill1,@Query("skill[2]") String skill2);
try
CompositeDisposable compositeDisposable = new CompositeDisposable();
compositeDisposable.add(ApiClient.getWebApiService().addskill(/*parameterhhere in your way*/)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::handleResults, this::handleError));
catch (Exception e)
e.printStackTrace();
HashMap<String,String> params = new HashMap<>();
int i = 0;
params.put("skill["+i+"]","0");
【讨论】:
以上是关于如何使用改造 Android 调用具有动态参数的 api?的主要内容,如果未能解决你的问题,请参考以下文章
如何在使用改造和 android jetpack 库时使用此动态 json 键创建数据类
C# Specflow:如何在另一个文件夹的类中调用具有动态表作为参数的方法