【发布时间】:2020-09-05 10:56:33
【问题描述】:
我正在尝试使用改造来使用我自己的 REST 调用。我关于它为什么不起作用的唯一线索是它说信息的类型是“text/html”,即使我确定它是 json。话虽如此,我还没有找到任何解决我问题的答案。
有效载荷:
[
{
"user_id": "32",
"username": "Marko",
"last_activity": "2020-04-26 20:44:00",
"user_image": "slika2"
},
{
"user_id": "33",
"username": "dejan",
"last_activity": "2020-04-26 20:44:00",
"user_image": "slika3"
}
]
我的聊天课:
public class Chat {
@SerializedName("user_id")
private String userId;
private String username;
@SerializedName("last_activity")
private String lastActivity;
@SerializedName("user_image")
private String userImage;\
...constructor/getters
}
API接口:
@FormUrlEncoded
@POST("api_get_all_chats.php")
Call<List<Chat>> getChats(
@Field("id") String id
);
API 客户端:
public static Retrofit getClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.level(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
retrofit = new Retrofit.Builder()
.baseUrl("http://MYIP/emob%20projekat/api/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit;
}
以及整个请求:
apiInterface = ApiClient.getClient().create(userApi.class);
Call<List<Chat>> call = apiInterface.getChats(u.getUserInfo().getUserId());
call.enqueue(new Callback<List<Chat>>() {
@Override
public void onResponse(Call<List<Chat>> call, Response<List<Chat>> response) {
chatList = new ArrayList<>(response.body());
chatAdapter = new ChatAdapter(getApplication().getApplicationContext(), R.layout.user_view, chatList);
listView.setAdapter(chatAdapter);
}
@Override
public void onFailure(Call<List<Chat>> call, Throwable t) {
Toast.makeText(getApplication().getApplicationContext(), "ne valja" , Toast.LENGTH_LONG).show();
}
});
任何我搞砸的线索都将不胜感激。
【问题讨论】:
-
尝试在 POSTMAN 中运行相同的请求
-
我做到了,而且效果很好。
-
什么是ip?是本地主机还是普通 IP 或公共 IP?
标签: android json api rest retrofit