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

joh*_*ohn 1 java git post curl 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
Run Code Online (Sandbox Code Playgroud)

现在我需要执行上面相同的 url,HttpClient并且我正在我的项目中使用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<String, String> parameters = new LinkedMultiValueMap<String, String>();
parameters.add("username", username);
parameters.add("password", password);

// Create the http entity for the request
HttpEntity<MultiValueMap<String, String>> entity =
            new HttpEntity<MultiValueMap<String, String>>(parameters, headers);

ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
Run Code Online (Sandbox Code Playgroud)

任何人都可以提供一个示例,我将如何通过向其发布 JSON 来执行上述 URL?

Zak*_*Mak 5

我还没有时间测试代码,但我相信这应该可以解决问题。当我们使用curl -u来传递凭据时,必须对其进行编码并与授权标头一起传递,如此处所述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<String> entity = new HttpEntity<String>(data, headers);    
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity , String.class);
Run Code Online (Sandbox Code Playgroud)