john
john

Reputation: 11709

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

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?

Upvotes: 1

Views: 3181

Answers (1)

ZakiMak
ZakiMak

Reputation: 2102

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

Upvotes: 5

Related Questions