其实我试图为我的办公室食堂制作一个Android应用程序,因为Spring Web应用程序已经存在。在Android应用程序中,我显示了当天可用的所有项目。员工将填写数量到相应的项目,然后提交。为此,我在Spring控制器中创建了一个webService,我可以通过REST访问android应用程序中的所有项目(使用getForObject
)。我已经将EditText的id作为item_id(从远程数据库使用rest获取),并且每当用户点击放置顺序时,我都会创建一个HashMap,因为我放置了item_id,为所有项目订购qty。但我面临着使用rest将HashMap发送到Spring Web应用程序的问题。我试图发送使用restTemplate.getForObject("http://172.16.1.2/webapp/rest/restPlaceOrder?order="+order, List.class);
。但它是以....../restPlaceOrder?order = {1 = 2,2 = 7,8 = 4}的形式接收的。正如你所说,我应该使用postForObject而不是getForObject。现在我试图在spring控制器中使用postForObject并使用@RequestBody。但是现在,无论何时我在Spring控制器中使用@RequestBody,android restclient都会给出错误不受支持的媒体类型。所以请帮助我使用postForObject发送HashMap,并在Spring控制器中捕获同样的东西。我使用的代码在Android客户端作为在Spring控制器中获取HashMap
HashMap<Integer, Integer> order=new HashMap<Integer, Integer>();
order.put(1, 5); order.put(2, 4);
String url="http://172.16.1.2/webapp/rest/restPlaceOrder"
RestTemplate restTemplate1=new RestTemplate();
restTemplate1.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
List<LinkedHashMap> res=restTemplate1.postForObject(url, null, List.class, order);
,并在春季控制器的Web应用程序,我使用
@RequestMapping(value="/restPlaceOrder", method= {RequestMethod.GET, RequestMethod.POST}, headers="Accept=application/json")
public @ResponseBody List<Schedule> placeOrder(@RequestBody HashMap<Integer, Integer> order, HttpServletRequest request, HttpServletResponse response, Model m){
System.out.println("welcome taking request");
/*problem is whenever i put @RequestBody, Restclient shows unsupported media type and if I remove @RequestBody, then it works but then how to get that HashMap here */
List<Schedule> sc=new ArrayList();
return sc;
}
你真的想你的URL看起来像'.../restPlaceOrder?order = {1 = 2,2 = 7,8 = 4}'?你不应该依赖HashMap的toString()来设计你的URL。这幅地图应该是什么?你的方法被命名为placeOrder()。因此,我认为它的目的是**创造**东西,而不是获得某种东西。所以它应该使用POST,而不是GET。 –
是啊,绝对正确。我想要处理的这张订单地图(Integer,Integer)是将一对(item_id,qty)存储到数据库中,但我不知道如何从静态webservice调用这个地图到spring控制器。 – ashok
正如我所说:使用POST而不是GET,将该Map作为请求的主体发送,而不是作为查询参数,并通过使用'@ RequestBody'而不是'@ RequestParam'注释参数在服务器上获取它。 。而且,由于您期待Map,因此将该方法参数的类型设置为对象。 –