سؤال

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();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top