How to Call an REST endpoint with basic auth from salesforce?

Dec 18, 2017    Janaki Mahapatra, Salesforce

In order to call an external server, we have to add the URL in Remote Site Settings. Click Setup > Security Controls > Remote Site Settings > New Add external site name and endpoint URL Site:cheenath endpoint url:https://yourendpoint.details/
public with sharing class ServiceClass {

    private final String AUHT_KEY = 'AUHT_KEY';
    private final String AUTH_USERNAME = 'AUTH_USERNAME';
    private final String AUTH_PASSWORD = 'AUTH_PASSWORD';
    private final String BASE_URL = 'BASE_URL';

	public Map myMethod(String requestUri,String requestBody){
		HttpRequest req = this.getRequest(requestUri);

		Http h = new Http();
		HttpResponse response = h.send(req);
		Map jsonMap = (Map) JSON.deserializeUntyped(response.getBody());
		return jsonMap;

	private HttpRequest getRequest(String endpoint) {

        Blob headerValue = Blob.valueOf(AUHT_KEY + '\\' + AUTH_USERNAME + ':' + AUTH_PASSWORD);
        String authHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);

        HttpRequest req = new HttpRequest();
        req.setEndpoint(BASE_URL + endpoint);
        req.setHeader('Authorization', authHeader);
        req.setHeader('Accept', 'application/json');
        req.setHeader('Content-Type', 'application/json');
        return req;
Now we can call the rest endpoint as
ServiceClass myService = new ServiceClass();
Map objResponse = myService.myMethod('getWebLead','{"LeadId":"12345"}');