如何在Android系统中动态地在retrofit中传递POST、GET等方法类型?

问题描述 投票:0回答:1
@GET
fun getAccountInfo(
    @Url url: String, @HeaderMap headers: Map<String, String>?
): Call<AccountInfoModel.Response>

如何动态地传递这个get方法,而不是声明静态的。

android retrofit2
1个回答
0
投票

在retrofit中,你不能使用动态http方法,你可以使用okhttp来实现,请看下面我的回答。

package in.silentsudo.test;

import com.google.gson.JsonObject;
import okhttp3.*;

import java.io.IOException;

public class OkHttpMain {
    public static void main(String[] args) throws IOException {
        OkHttpClient client = new OkHttpClient();

        final String host = "https://reqres.in/";

        System.out.println(get(host + "api/users/1", client));


        JsonObject postBody = new JsonObject();
        postBody.addProperty("name", "morpheus");
        postBody.addProperty("job", "leader");

        System.out.println(post(host + "api/users", postBody.toString(), client));
    }

    static String get(String url, OkHttpClient client) throws IOException {
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    static String post(String url, String json, OkHttpClient client) throws IOException {
        final MediaType JSON
                = MediaType.get("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(json, JSON);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }
}

OkHttp参考。https:/github.comsquareokhttp。

© www.soinside.com 2019 - 2024. All rights reserved.