[英]Translate authorized curl -u post request with JSON data to RestTemplate equivalent
我正在使用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<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);
任何人都可以舉例說明如何通過向其發布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<String> entity = new HttpEntity<String>(data, headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity , String.class);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.