问题描述
第一次使用REST并尝试在REST请求URL中发送JSON字符串作为路径变量,我正在做什么来从客户端发送请求:
Using REST for the first time and trying to send JSON string as path variable in REST request URL, what I am doing to send a request from client:
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);
休息服务器:
@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;
}
我得到的例外是不够变量值以扩展测试
编辑:我的请求网址如下所示:
my request url looks like this:
的http://本地主机:8090 /应用/ restResource /%7B%22%22:%22123 22%,%22tracks%22:%221234%22%7D.do
甚至看到了HttpClientErrorException!任何帮助表示赞赏!
Even saw the HttpClientErrorException! Any help is appreciated!
推荐答案
我要做的是:
HttpEntity<Object> entity = new HttpEntity<Object>(json); // Create HTTP Entity to post to rest endpoint
restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
restTemplate.postForEntity(url, entity, Object.class);
在服务器端,您不需要以PathVariable的形式访问它,而是可以使用
In your server side, you do not need to access this as PathVariable instead you can use
@RequestMapping(value = "/restresource", method=RequestMethod.POST, consumes= "application/json")
public @ResponseBody String useJson(@RequestBody JSonObject object) {
因此spring框架自动将json字符串转换为指定的对象类型。
您可以相应调整您的网址,然后重试。
Hence spring framework automatically convert the json string into the specified object type.You can adjust your URL accordingly and try again.
这篇关于在REST URL中传递JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!