【发布时间】:2015-03-06 10:20:09
【问题描述】:
我正在设置一个带有改造的 api 客户端,到目前为止 GET 工作正常,但我正在尝试使用 POST 创建一个新对象,而不是将对象作为 json 发送,请求正文只是包含字符串“null”:
---> HTTP POST http://myapiurl
Content-Type: application/json; charset=UTF-8
Content-Length: 4
null
---> END HTTP (4-byte body)
这是我试图调用的方法:
@POST("/Monsters/")
Response new_monster(@Body Monster mon);
我是这样称呼它的:
@Test
public void testNew_monster() throws Exception {
//create a new monster object, and pass it to the function,
//then query and verify it's in the results?
Monster newmon = new Monster() {
{
name = "deleteme";
description = "created by junit test testNew_monster";
image_url = "http://i.imgur.com/";
created_by = "";
encoded_key = "";
}
};
Response r = client.new_monster(newmon);
assertEquals(201, r.getStatus());
//sleep a couple seconds here?
List<Monster> monsterList = client.monsters();
assertTrue(monsterList.contains(newmon));
}
我猜想在使用 GSON 将对象序列化为 json 时出现问题,但在序列化过程中我看不到任何对调试器有帮助的东西...
我使用的是 GSON 2.3.1 版
编辑:这是我构建 RestAdapter 和客户端的方式:
static MonSpottingApi GetClient(boolean dbg)
{
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API_URL)
.build();
if (dbg) restAdapter.setLogLevel(RestAdapter.LogLevel.FULL);
MonSpottingApi client = restAdapter.create(MonSpottingApi.class);
return client;
}
在测试用例类中:
MonSightingClient.MonSpottingApi client;
@Before
public void setUp() throws Exception {
client = MonSightingClient.GetClient(true);
}
【问题讨论】:
-
如何为客户端界面构建
RestAdapter? -
@EfeKahraman 我在问题中添加了更多代码以显示这一点。
-
我认为您可能在 Builder 中遗漏了一些方法调用。检查the RestAdapter.Builder documentation,它说你应该添加
setEndpoint(Endpoint)、setClient(Client.Provider)和setConverter(Converter)