将授权的curl -u post请求与JSON数据转换为RestTemplate等效项

我正在使用github api使用curl命令创建存储库,如下所示,它工作正常。

curl -i -u "username:password" -d '{ "name": "TestSystem", "auto_init": true, "private": true, "gitignore_template": "nanoc" }' https://github.host.com/api/v3/orgs/Tester/repos 

现在我需要通过HttpClient执行相同的上面的url,我在我的项目中使用RestTemplate

我之前使用过RestTemplate ,我知道如何执行简单的url但不知道如何使用RestTemplate将上述JSON数据发布到我的url –

 RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); // Create a multimap to hold the named parameters MultiValueMap parameters = new LinkedMultiValueMap(); parameters.add("username", username); parameters.add("password", password); // Create the http entity for the request HttpEntity<MultiValueMap> entity = new HttpEntity<MultiValueMap>(parameters, headers); ResponseEntity response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class); 

任何人都可以举例说明如何通过向其发布JSON来执行上述URL?

我没有时间测试代码,但我相信这应该可以解决问题。 当我们使用curl -u时 ,要传递凭证,必须对其进行编码并与Authorization标头一起传递,如http://curl.haxx.se/docs/manpage.html#-basic所述 。 json数据只是作为HttpEntity传递。

 String encoding = Base64Encoder.encode("username:password"); HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Basic " + encoding); headers.setContentType(MediaType.APPLICATION_JSON); // optional String data = "{ \"name\": \"TestSystem\", \"auto_init\": true, \"private\": true, \"gitignore_template\": \"nanoc\" }"; String url = "https://github.host.com/api/v3/orgs/Tester/repos"; HttpEntity entity = new HttpEntity(data, headers); RestTemplate restTemplate = new RestTemplate(); ResponseEntity response = restTemplate.exchange(url, HttpMethod.POST, entity , String.class);