我正在使用spring的mvc(基于注释)和java。我需要在我的应用程序中执行其他API。我对API和REST都很新。在我的休息申请中需要做的所有基本配置是什么?我打算使用“RestTemplate” 如何使用RestTemplate进行基本身份验证(在URL标头中传递用户名和密码)?请任何人帮助我。使用RestTemplate Rest Rest API的基本认证
在此先感谢。
我正在使用spring的mvc(基于注释)和java。我需要在我的应用程序中执行其他API。我对API和REST都很新。在我的休息申请中需要做的所有基本配置是什么?我打算使用“RestTemplate” 如何使用RestTemplate进行基本身份验证(在URL标头中传递用户名和密码)?请任何人帮助我。使用RestTemplate Rest Rest API的基本认证
在此先感谢。
您必须添加authetication头(其中Base64是例如从org.apache.commons.codec.binary.Base64
):
String plainCreds = "[email protected]";
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()
方法
而不是“@”你必须把“:”
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();