2

I am developing a batch class to make api calls and get data from that api in to salesforce. I need to send http request by post method, with user name & password as header. I have tried but i got error. Can anyone please help me to do this. Below is my code please check it.

    HttpRequest req= new HttpRequest();
    req.setMethod('POST');
    String username = 'ABC';
    String password = 'Sales123'; 
    Blob headerValue = Blob.valueOf(username + ':' + password);
    String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
    req.setHeader('Authorization', authorizationHeader);
    Http http = new Http();       
    String url = 'http://XYZ';
    req.setEndpoint(url );
    HttpResponse res = http.send(req);
    return res.getBody(); 
  • what is the error? – AtulRajguru9 Feb 6 '15 at 6:08
  • Invalid Request error was encountered while trying to process the request: – Nayana Pawar Feb 6 '15 at 6:10
  • Please reply me. – Nayana Pawar Feb 6 '15 at 6:24
  • Usually the service you're trying to call will give you an example of how to authenticate. Have you checked? – ArtieBrosius May 8 '15 at 18:25
  • Use a tool like WSDLER to test the call. On successful call look at headers. I would start there. – Berg Aug 19 '15 at 10:30
1

I recognize that at the time of posting this, this question is 3 yrs old. One possible answer to this question is the service provider was using an OAUTH2_USERNAME_PASSWORD context. When that's the case, the header would likely need to use different parameters which are usually at the discretion of the provider.

When that's the case, the org will be provided with a clientKey (also referred to as clientId) and a ConsumerSecret that together when base64encrypted, will create an access token that must be included to in the header. These can be specified in the definition of a Named Credential which is convenient to use as a means of handling authentication for the API user with a provider.

Named credentials can also be referenced when creating an Http request using field references as per the documentation in Merge Fields for Apex Callouts That Use Named Credentials. The same page provides examples of some valid values to use when the Named Credential uses this method for authentication:

{!$Credential.AuthorizationMethod}
  • Basic—password authentication
  • Bearer—OAuth 2.0
  • null—no authentication

Similarly, for header values:

{!$Credential.AuthorizationHeaderValue}

Valid values depend on the authentication protocol of the named credential.

  • Base-64 encoded username and password—password authentication
  • OAuth token—OAuth 2.0
  • null—no authentication

Finally, if the named credential uses OAuth authentication, there's:

{!$Credential.OAuthConsumerKey}
{!$Credential.OAuthToken}

// If the external system expects “OAuth” as
// the prefix for the access token.
// Then the following would be used for the running user:
req.setHeader('Authorization', 'OAuth {!$Credential.OAuthToken}');
| improve this answer | |
0

Try something like this:

Note 2 changes:
1) setMethod('GET');
2) Basic not BASIC

HttpRequest req= new HttpRequest();
req.setMethod('GET');
String username = 'ABC';
String password = 'Sales123'; 
Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'Basic  ' + EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authorizationHeader);
Http http = new Http();       
String url = 'http://XYZ';
req.setEndpoint(url );
HttpResponse res = http.send(req);
return res.getBody(); 
| improve this answer | |
  • But our requirement is to set POST Method. – Nayana Pawar Feb 6 '15 at 7:10
  • Most of time i have used Get but you can try using POST and see what happens – AtulRajguru9 Feb 6 '15 at 8:17
  • Still got same error. – Nayana Pawar Feb 6 '15 at 8:22
  • Can you post the complete code here? – the_phantom May 8 '15 at 18:23
0
Try this.

    Http httpProtocol = new Http();
    HttpRequest request= new HttpRequest();
    String url = 'http://XXXXXX';
    request.setEndpoint(url);
    request.setMethod('POST');
    request.setHeader('Authorization', getBasicAuthHeader('ABC','Sales123'));
    HttpResponse response = httpProtocol.send(request);

 public static String getBasicAuthHeader(String username, String password){
      String authHeader = '';        
      authHeader = (username != null && password != null) ? 'Basic ' + EncodingUtil.base64Encode(Blob.valueOf(username + ':' + password)) : '';      
      System.debug('Using Basic Authentication Header: ' + authHeader);        
      return authHeader;   
}
| improve this answer | |
0

Sample Code:

public static HttpResponse makePostCallout() {

    String jsonOrders ='{JSON FORMAT BODY OF THE DATA}}';
        Http http = new Http();
        HttpRequest request2 = new HttpRequest();
        request2.setEndpoint('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
        request2.setMethod('POST');
        request2.setHeader('Content-Type', 'application/json; charset=utf-8');
        request2.setHeader('scope', 'XXXXXXXXXXX');
        request2.setHeader('Accept', '*/*');
        request2.setBody(jsonOrders);

        String username = 'XXXXXXXXXXX';
        String password = 'XXXXXXXXXXXXXX';
        Blob headerValue = Blob.valueOf(username + ':' + password);
        String authorizationHeader = 'Basic ' +
        EncodingUtil.base64Encode(headerValue);
        request2.setHeader('Authorization', authorizationHeader);
        //HttpResponse response = http.send(request2);
       // system.debug('The Response Body: '+response.getBody());

        HttpResponse response2 = http.send(request2);

        // Parse the JSON response
        if (response2.getStatusCode() != 201) {
            System.debug('The status code returned was not expected: ' +
                response2.getStatusCode() + ' ' + response2.getStatus());
        } else {
            System.debug(response2.getBody());
        }
        return response2;
    }        

Please let me know if this resolves your issue.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.