问题相关代码 kotlin上手好难 = - =
HttpUtil.get(
"/prod-api/api/rotation/list",
mapOf(),
KJbanner::class.java,
object : HttpUtil.Callback<KJbanner> {
override fun callback(json: String, t: KJbanner) {
}
})
这是我的工具类
object HttpUtil {
private val gson = Gson()
fun <T> get(
url: String,
query: Map<String, String>,
clazz: Class<T>,
callback: Callback<T>
) {
val bodyCall = api.get(url, header, query)
enqueue(bodyCall, clazz, callback)
}
private fun <T> enqueue(
bodyCall: Call<ResponseBody>,
clazz: Class<T>,
callback: Callback<T>
) {
bodyCall.enqueue(object : retrofit2.Callback<ResponseBody> {
override fun onFailure(p0: Call<ResponseBody>, p1: Throwable) {
Log.d(clazz.name, "网络请求错误$p1")
}
override fun onResponse(p0: Call<ResponseBody>, p1: Response<ResponseBody>) {
val json = p1.body()!!.string()
val t = gson.fromJson(json, clazz)
Log.i(clazz.name, "onResponse: $json")
callback.callback(json, t)
}
})
}
interface Callback<T> {
fun callback(json: String, t: T)
}
private val header: Map<String, String>
get() {
val map = HashMap<String, String>()
if (DataUtil.token != null) {
map["Authorization"] = DataUtil.token!!
}
return map
}
private val api: Api = Retrofit.Builder().baseUrl(DataUtil.url).build().create(Api::class.java)
private interface Api {
@GET
fun get(
@Url string: String,
@HeaderMap header: Map<String, String>?,
@QueryMap query: Map<String, String>
): Call<ResponseBody>
}
}
我的解答思路和尝试过的方法
我想要达到的结果 : 当我用java写的工具类时
HttpUtil.get("/sc2/lib/comment/list", mapOf, KJlibcomments::class.java) { json, t ->
}
public class HttpUtil {
private static Gson gson = new Gson();
public static <T> void get(String address, Map<String, String> query, Class<T> cls, Callback<T> callback) {
if (query == null) query = new HashMap<>();
Call<ResponseBody> bodyCall = getApi().get(DataUtil.url + address, getHead(), query);
enqueue(bodyCall, cls, callback);
}
private static <T> void enqueue(Call<ResponseBody> bodyCall, final Class<T> cls, final Callback<T> callback) {
bodyCall.enqueue(new retrofit2.Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String json = response.body().string();
Log.d(cls.getName() + "json", "onResponse: " + json);
T t = gson.fromJson(json, cls);
callback.callback(json, t);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable throwable) {
Log.d(cls.getName(), "网络请求错误" + throwable.toString());
}
});
}
private static Map<String, String> getHead() {
HashMap<String, String> map = new HashMap<>();
if (DataUtil.token != null) map.put("Authorization", DataUtil.token);
return map;
}
private static Api getApi() {
Retrofit retrofit = new Retrofit.Builder().baseUrl(DataUtil.url).build();
return retrofit.create(Api.class);
}
public interface Callback<T> {
void callback(String json, T t);
}
interface Api {
@GET
Call<ResponseBody> get(@Url String url, @HeaderMap Map<String, String> header, @QueryMap Map<String, String> query);
}