我正在设置一个改装的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);
}
答案 0 :(得分:1)
我怀疑根本原因是Gson,所以我开始进行非常简单的测试并尝试使用toJson()来使对象正确序列化。我想我在Gson中发现了一个错误,如果使用双括号语法初始化对象,它会失败:
使用找到here
的示例类public class GitHubTest {
//fails
@Test
public void testGson1() throws Exception {
GitHubClient.Contributor contrib = new GitHubClient.Contributor() {
{
login = "someguy";
contributions = 99;
}
};
Gson gson = new Gson();
String json = gson.toJson(contrib);
System.out.println("contents of json string: " + json);
assertNotEquals(json, "null");
}
//passes
@Test
public void testGson2() throws Exception {
GitHubClient.Contributor contrib = new GitHubClient.Contributor();
contrib.contributions = 99;
contrib.login = "someguy";
Gson gson = new Gson();
String json = gson.toJson(contrib);
System.out.println("contents of json string: " + json);
assertNotEquals(json, "null");
}
}
这是Gson中的错误吗?或者是否有一些奇怪的微妙Java原因会发生这种情况? (Java不是我最强的语言)。
答案 1 :(得分:0)
您必须将接口类传递给create()
Restadapter
方法。我们假设您的界面类是INewService
(您声明为new_monster
),然后GetClient
应该是这样的:
public static INewService GetClient(boolean dbg){
RestAdapter restAdapter = new RestAdapter.Builder().
.setEndpoint(API_URL).
.setClient(new OkClient(new OkHttpClient()))
.build();
if (dbg) restAdapter.setLogLevel(RestAdapter.LogLevel.FULL);
return restAdapter.create(INewService.class);
}