The new Named Credentials feature streamlines and simplify the process of using authenticating with third party web services within Apex code.
Named Credentials can be used with for both HTTP Basic authentication (Password Authentication) and OAuth 2.0 authentication and can be set up on a per user or organization-wide (Named Principal) basis.
Why to use Named Credentials
Authentication is done by Salesforce and you need not to worry about that.
No need to create a Remote Site Setting if using a Named Credential.
Callout is easier to maintain. No hard coding involved.
If are also using Sandboxes for callout, just create the Named Credentials with the same name and save different URL.
Follow these steps to create a named credential
1) From Setup, click Security Controls -> Named Credentials.
2) Click New Named Credential, or click Edit to modify an existing named credential.
3) Complete the fields.
HTTP Basic authentication
[content_box type=”” title=”Without Named credential” icon=”” color=”” text_color=”” animation=”” animation_delay=”” class=””]
HttpRequest req = new HttpRequest();
req.setEndpoint(‘https://abc.example.com/path’);
req.setMethod(‘GET’);
String username = ‘username’;
String password = ‘password’;
Blob headerValue = Blob.valueOf(username + ‘:’ + password);
String authorizationHeader = ‘BASIC ‘ + EncodingUtil.base64Encode(headerValue);
req.setHeader(‘Authorization’, authorizationHeader);
Http http = new Http();
HttpResponse res = http.send(req);
System.debug(res.getBody());
[content_box type=”” title=”With Named credential” icon=”” color=”” text_color=”” animation=”” animation_delay=”” class=””]
first create a named credential as following
Label : HTTP Basic Credential
Name : HTTP_Basic_Credential
URL : https://abc.example.com/
Identity Type : Named Principal
Authentication Protocol : Password Authentication
Username : username
Password : password
After that use Named Credential as follows
HttpRequest req = new HttpRequest();
req.setEndpoint(‘callout:HTTP_Basic_Credential/path’);
req.setMethod(‘GET’);
Http http = new Http();
HttpResponse res = http.send(req);
System.debug(res.getBody());