简体   繁体   中英

Basic authendication for Rest API using RestTemplate

I am using spring mvc(Annotation based) with java. I need to do rest API in my application. I am very new to both API and REST. What are all the basic configuration need to do in my application for Rest? I plan to use "RestTemplate" How to do the Basic authentication(passing username and password in URL headers) with RestTemplate ? Please anyone help me.

Thanks in advance.

You have to add authetication header (where Base64 is for example from org.apache.commons.codec.binary.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);

and then add it into request:

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

For POST requests you can pass HttpEntity to standard postForObject() method

instead of "@" you must put ":"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM