我在我的应用程序中使用Retrofit Library来处理网络请求。我的代码如下:
1。 MyAPI.java(接口)
public interface MyAPI {
@GET("/{roomID}")
Call<Messages>loadMessages(@Path("roomID") String roomID);
}
2。 Message.java
public class Message {
String user;
String message;
//String roomID;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return(message);
}
}
3.Messages.java
public class Messages {
List<Message> items;
}
4.MainActivity.java
public class MainActivity extends AppCompatActivity {
String roomID = "548b737c0eadfb00eb93891bb28242e5";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://pms.vebific.com:81/chat/index/")
.addConverterFactory(GsonConverterFactory.create())
.build();
MyAPI myAPI = retrofit.create(MyAPI.class);
Call<Messages> call = myAPI.loadMessages(roomID);
call.enqueue(new Callback<Messages>() {
@Override
public void onResponse(Response<Messages> response, Retrofit retrofit) {
Log.e("Response", String.valueOf(response.body()));
}
@Override
public void onFailure(Throwable t) {
Log.e("Error","---------------");
}
});
}
}
要使用的网址是:
http://pms.vebific.com:81/chat/index/548b737c0eadfb00eb93891bb28242e5
预期回复:
[
{
"_id": {
"$id": "56963d96da036c6c05815e63"
},
"room_id": "548b737c0eadfb00eb93891bb28242e5",
"user": "Jeevan Verma",
"id": 479,
"message": "\\uD83D\\uDC30",
"date": 1481587559734,
"status": "sent"
},
{
"_id": {
"$id": "56963d8cda036c6c05815e62"
},
"room_id": "548b737c0eadfb00eb93891bb28242e5",
"user": "Jeevan Verma",
"id": 479,
"message": "\\uD83D\\uDE0A",
"date": 1481587559734,
"status": "sent"
},
{
"_id": {
"$id": "56964454da036c6c05815e64"
},
"room_id": "548b737c0eadfb00eb93891bb28242e5",
"user": "Jeevan Verma",
"id": 479,
"message": "\\uD83D\\uDC2D",
"date": 1481589296434,
"status": "sent"
}
]
当我在浏览器中使用它时,我得到了回复。
在使用Retrofit时,我得到空响应。我猜可能会遗漏一些东西。请帮我解决。请告诉我如何使用Retrofit阅读回复。
答案 0 :(得分:2)
将您的api定义更改为Call<List<Message>>
而不是Call<Messages>
:
Call<List<Message>>loadMessages(@Path("roomID") String roomID);
和
MyAPI myAPI = retrofit.create(MyAPI.class);
Call<List<Message>> call = myAPI.loadMessages(roomID);
call.enqueue(new Callback<List<Message>>() {
@Override
public void onResponse(Response<List<Message>> response, Retrofit retrofit) {
Log.e("Response", String.valueOf(response.body()));
}
@Override
public void onFailure(Throwable t) {
Log.e("Error","---------------");
}
});