Translate authorized curl -u post request with JSON data to RestTemplate equivalent

妖精的绣舞 提交于 2019-12-08 05:18:48

问题


I am using github api to create repositories using curl command as shown below and it works fine.

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

Now I need to execute the same above url through HttpClient and I am using RestTemplate in my project.

I have worked with RestTemplate before and I know how to execute simple url but not sure how to post the above JSON data to my url using RestTemplate -

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);

Can anyone provide an example how would I execute the above URL by posting JSON to it?


回答1:


I have not had the time to test the code, but I believe this should do the trick. When we are using curl -u, to pass the credentials, it has to be encoded and passed along with the Authorization header, as noted here http://curl.haxx.se/docs/manpage.html#--basic. The json data, is simply passed as a 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);


来源:https://stackoverflow.com/questions/28390662/translate-authorized-curl-u-post-request-with-json-data-to-resttemplate-equival

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!