如何使用 Spring 的 RestTemplate 发布 JSON 数据?



鉴于我找到的例子,我不太明白如何解决我的特殊情况。我试图将JSON字符串发布到URL以创建新对象。来自REST服务的响应是一个指向新创建资源的URI。REST调用应该是这样的:

http://www.some.url.com/REST/create?data={ "param1":"value1", "param2":"value2", ... }
那么根据上面的例子,我的参数是什么呢?是这样的吗?
RestTemplate restTemplate = new RestTemplate();
URI uri = restTemplate.postForLocation("http://www.some.url.com/REST/create?data=", "{ "param1":"value1", "param2":"value2", ... }");

我目前有所有的参数/值对在一个地图,可以很容易地转换为JSON使用杰克逊。在这种情况下,我可以做以下操作吗?

Map<String, String> record = new HashMap<String, String>();
record.put("param1","value1");
record.put("param2","value2");
URI uri = restTemplate.postForLocation("http://www.some.url.com/REST/create?data=", record);

任何帮助都将非常感激!

这是一个简单的方法

public static String callService(String url, Map<String, String> data) throws Exception 
{RestTemplate rest = new RestTemplate();
ResponseEntity<String> response= rest.postForEntity(url, data, String.class);
            System.out.println(response.getBody()); 
}

最新更新