我在mLab.com上运行了RESTful MongoDB。 我想通过Retrofit(已经可以正常工作)从此MongoDB中获取JSON,然后在更新其中的一些信息之后进行PUT / POST /更新文件。
这是我当前的界面:
public interface UsersAPI {
@Headers("Content-Type: application/json")
@GET("5b3f67e2e7179a2eb16f1a17?apiKey=AyWtAV3TMB-iMtXcEimhVuK5Ar32VSaF")
Call<UserObject> getUsers();
@POST("5b3f67e2e7179a2eb16f1a17?apiKey=AyWtAV3TMB-iMtXcEimhVuK5Ar32VSaF")
Call<UserObject> setUsers(@Body Users blabla);
@PUT("5b3f67e2e7179a2eb16f1a17?apiKey=AyWtAV3TMB-iMtXcEimhVuK5Ar32VSaF")
Call<UserObject> setUsers();
}
这是函数:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
// Call GET
UsersAPI get = retrofit.create(UsersAPI.class);
Call<UserObject> call = get.getUsers();
// Call PUT
UsersAPI put = retrofit.create(UsersAPI.class);
final Call<UserObject> call2 = put.setUsers();
call.enqueue(new Callback<UserObject>() {
@Override
public void onResponse(Call<UserObject> call, Response<UserObject> response) {
ArrayList<Users> userList = (ArrayList<Users>) response.body().getUsers();
Log.d(TAG, "\n \n Server Response: " + response.body().toString());
for (int i =0; i<userList.size(); i++) {
Log.d(TAG, "onResponse: \n" +
"Username: " + userList.get(i).getUsername() + "\n" +
"Geschlecht: " + userList.get(i).getGender() + "\n" +
"Alter: " + userList.get(i).getAge() + "\n" +
"Bike: " + userList.get(i).getBike() + "\n" +
"Gefahrene Meter: " + userList.get(i).getAmountBiked() + "\n" +
"Gefahrene Zeit in Minuten: " + userList.get(i).getDurationBiked() + "\n" +
"Bike Skill: " + userList.get(i).getBikeSkill() + "\n" +
"--------------------------------------------------------------------------\n\n");
int bikeSkill = userList.get(i).getAmountBiked() + userList.get(i).getDurationBiked();
if (bikeSkill <= 10000) {
userList.get(i).setBikeSkill("Anfänger");
} else if (bikeSkill <=30000) {
userList.get(i).setBikeSkill("Fortgeschritten");
} else {
userList.get(i).setBikeSkill("Profi");
}
}
}
GET请求按预期完全正常运行。此外,setBikeskill();正在执行预期的操作:更改后我在进行打印时会对其进行本地更新。但是我不知道如何将文件恢复到服务器上,因为我无法在GET队列中将PUT或POST请求排队。
这是针对大学项目的,因此代码不会特别干净且命名合理,但我希望您仍然能够掌握要点。