【发布时间】:2021-01-13 22:28:41
【问题描述】:
我无法让 POST http 请求正常工作。似乎我没有正确使用retrofit2库,但根据我的研究,我应该可以工作。
这是我的简化对象类的样子:
public class Tournament {
private String name;
private int nOfGames;
private String game;
private String userId;
public Tournament(String name, int nOfGames, String game, String userId) {
this.name = name;
this.nOfGames = nOfGames;
this.game = game;
this.userId = userId;
}
}
我尝试了两种方法:
方法一:
改造界面:
@Headers({"Content-Type: application/json;charset=UTF-8"})
@POST("TournamentApi/")
Single<Tournament> createTournament(@Body Tournament tournament);
使用:
Tournament tournament = new Tournament(
"some name",
2,
"some game",
"1");
api.createTournament(tournament);
方法 2:
改造界面:
@FormUrlEncoded
@POST("TournamentApi/")
public void insertTournament(
@Field("Name") String name,
@Field("NOfGames") int nOfGames,
@Field("Game") String game,
@Field("UserId") String userId,
Callback<Response> callback);
使用:
api.insertTournament(
tournamentName.getText().toString(),
Integer.parseInt(bestOfN.getText().toString()),
gameName.getText().toString(),
"1",
new Callback<Response>() {
@Override
public void onResponse(Call<Response> call, Response<Response> response) {
String output = call.toString();
String responze = response.toString();
}
@Override
public void onFailure(Call<Response> call, Throwable t) {
String output = call.toString();
}
});
第一种方法根本没有做任何事情,没有错误,什么都没有。我什至尝试使用 HttpLoggingInterceptor ,但什么也没有出现。似乎没有提出任何要求。第二种方法使我的应用程序完全崩溃,因为我收到 No Retrofit annotation found. (parameter #1) 错误,但我看到其他帖子相同的 sn-ps 没有任何关于回调的注释,据说是有效的。
我还使用 retrofit2 来获取工作正常的请求,它只是发布我无法工作的请求。
最后,如果我将它与 Postman 一起使用,则可以完美运行(将条目插入数据库):
POST http://192.168.1.124:5001/api/TournamentApi
{
"Name": "blabla_tournament",
"NOfGames": 3,
"Game": "some_game",
"UserId": "5"
}
我怀疑这与 localhost 有关,但由于 get 请求的工作方式与应有的一样,我很确定问题是我使用了 retrofit2 错误。
【问题讨论】:
-
API POST 请求的响应是什么?
标签: java android retrofit retrofit2