Hello friends, today we will learn how to Implement Basic Auth Integration (Rest API) in Apex Salesforce. In this Integration, we use a username and password.
Also check this: Get Weather Info in Apex Rest API
Basic auth is very simple, and we can easily implement this in our apex code.
In this integration method, The server requires users’ credentials in the form of a base64 encoded string in the Authorization header.
Code :
BasicAuth.cls :
public class BasicAuth{
public void CallBasicAuth(){
//use for send request
Http http = new Http();
// use for set all parameter
HttpRequest req = new HttpRequest();
String endpoint = 'https://www.myurl.com/endpoint'
req.setEndpoint(endpoint);
req.setMethod('POST');
req.setHeader('Content-Type','application/text');
String username = 'Username';
String password = 'Password';
// convert in Blob
Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'BASIC ' +EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authorizationHeader);
// HTTPResponse to get response from send request
HTTPResponse res = http.send(req);
System.debug('Response Status Code==> '+res.getStatusCode());
System.debug('Response Status==> '+res.getStatus());
if(res.getStatusCode() == 201 || res.getStatusCode() == 200){
System.debug('Response Body==> 'res.getBody());
}else{
//handler error
}
}
}
Reference :
What’s your Reaction?
+1
+1
+1
+1
+1
+1
2