使用RestTemplate对Rest API进行基本身份验证

时间:2014-01-15 07:28:57

标签: java api spring-mvc resttemplate

我正在使用带有java的spring mvc(基于注释)。我需要在我的应用程序中执行rest API。我对API和REST都很陌生。在我的Rest应用程序中需要做的所有基本配置是什么?我打算用“RestTemplate” 如何使用RestTemplate进行基本身份验证(在URL头中传递用户名和密码)?请有人帮助我。

提前致谢。

2 个答案:

答案 0 :(得分:4)

您必须添加验证标头(例如,来自org.apache.commons.codec.binary.Base64的Base64):

String plainCreds = "yourUsername@yourPassword";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);

然后将其添加到请求中:

HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<YourResponseType> response = restTemplate.exchange(url, HttpMethod.GET, request, YourResponseType.class);
YourResponseType account = response.getBody();

对于POST请求,您可以将HttpEntity传递给标准postForObject()方法

答案 1 :(得分:1)

代替&#34; @&#34;你必须把&#34;:&#34;

String plainCreds = "yourUsername:yourPassword";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);

HttpEntity<String> httpEntity = new HttpEntity<String>(headers);
ResponseEntity<YourResponseType> response = restTemplate.exchange(url, HttpMethod.GET, httpEntity, YourResponseType.class);
YourResponseType account = response.getBody();