在REST URL中传递JSON字符串

首次使用REST并尝试在REST请求URL中将JSON字符串作为路径变量发送,我正在做什么来从客户端发送请求:

JSONObject json = new JSONObject(); try { json.put("Test", "123"); json.put("tracks", "1234"); jj = json.toString(); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String url = "http://localhost:8090/webApp/restresource/"+jj+".do"; st = (String) restTemplate.postForObject(url,jj, String.class, jj); 

rest服务器:

 @RequestMapping(value = "/restresource/{code}", method=RequestMethod.POST, consumes= "application/json") public @ResponseBody String useJson(@PathVariable String jj) { String result; JSONObject jObject = new JSONObject(); try { result = jObject.getJSONObject(jj).toString(); } catch (JSONException jse) { jse.printStackTrace(); } return result; } 

我得到的例外是not enough variable values to expand "Test"

编辑:我的请求url如下所示:

http://localhost:8090/app/restResource/%7B%22%22:%22123%22,%22tracks%22:%221234%22%7D.do

甚至看到了HttpClientErrorException! 任何帮助表示赞赏!

我会做的是:

 HttpEntity entity = new HttpEntity(json); // Create HTTP Entity to post to rest endpoint restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter()); restTemplate.postForEntity(url, entity, Object.class); 

在您的服务器端,您无需像PathVariable那样访问它,而是可以使用

 @RequestMapping(value = "/restresource", method=RequestMethod.POST, consumes= "application/json") public @ResponseBody String useJson(@RequestBody JSonObject object) { 

因此spring框架自动将json字符串转换为指定的对象类型。 您可以相应调整您的url,然后重试。

你可以在下面使用

          org.codehaus.jackson jackson-mapper-asl 1.7.1   org.springframework org.springframework.web 3.1.1.RELEASE