我正在使用这个方法的RESTfull webservice:
@POST
@Consumes({"application/json"})
@Path("create/")
public void create(String str1, String str2){
System.out.println("value 1 = " + str1);
System.out.println("value 2 = " + str2);
}
Run Code Online (Sandbox Code Playgroud)
在我的Android应用中,我想调用此方法.如何使用org.apache.http.client.methods.HttpPost为参数赋予正确的值;
我注意到我可以使用注释@HeaderParam并简单地将标头添加到HttpPost对象.这是正确的方法吗?这样做:
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("str1", "a value");
httpPost.setHeader("str2", "another value");
Run Code Online (Sandbox Code Playgroud)
在httpPost上使用setEntity方法将不起作用.它仅使用json字符串设置参数str1.使用时如:
JSONObject json = new JSONObject();
json.put("str1", "a value");
json.put("str2", "another value");
HttpEntity e = new StringEntity(json.toString());
httpPost.setEntity(e);
//server output: value 1 = {"str1":"a value","str2":"another value"}
Run Code Online (Sandbox Code Playgroud) 我正在编写测试来验证我可以在我们的API上发布通用表单.
我还添加了一些调试,但我注意到实际表单发布的数据; (邮差/ AngularJS或w/e)不同于做mockMVC测试,如:
MvcResult response = mockMvc
.perform(post("/some/super/secret/url") //
.param("someparam1", "somevalue") //
.param("someparam2", "somevalue") //
.contentType(MediaType.APPLICATION_FORM_URLENCODED) //
.accept(MediaType.APPLICATION_JSON)) //
.andExpect(status().isOk()) //
.andReturn();
Run Code Online (Sandbox Code Playgroud)
配置与生产中运行的配置完全相同,等等.但是当我的拦截器记录内容时,在实际测试(而不是mockMVC)中,内容的格式为"someparam1 = somevalue&etc = encore"
当我打印mockMVC内容时,我实际上似乎没有内容,但请求中有Params,我认为它们像GET参数一样被添加.
有谁知道如何正确测试这个?我遇到了这个问题,因为看起来我们的表单帖子似乎没有被Spring解析,即使我们已经将FormHttpMessageConverter添加到servlet上下文中.