I am trying to rewrite the following Java HTTP request in Salesforce.
String apiUrl = "url";
String wsUser = "YourWSUser";
String wsPassword = "YourWSPassword";
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(wsUser, wsPassword);
provider.setCredentials(AuthScope.ANY, credentials);
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
HttpPost httpRequest = new HttpPost(apiUrl);
httpRequest.addHeader("Content-Type", "application/json");
httpRequest.setEntity(new StringEntity(paymentRequest.toString(), "UTF-8"));
HttpResponse httpResponse = client.execute(httpRequest);
String paymentResponse = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
This is what I wrote in APEX:
HttpRequest req = new HttpRequest();
req.setEndpoint(apiUrl);
req.setMethod('POST');
Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authorizationHeader);
req.setHeader('Content-Type', 'application/json');
req.setBody(generator.getAsString());
req.setTimeout(60000);
Http http = new Http();
HTTPResponse res = http.send(req);
My questions are:
- Is the conversion correct?
- If so any idea why I get a 401 as if my credentials are not set correctly. (knowing that the credentials and end point is correct)