1

I am trying to implement send a request to an external URL. External URL: https://testWeb.xxx.com This is a sample Java implementation of this:

   HttpPost post = new HttpPost(url.toString());
            post.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML.toString());
            post.setEntity(new ByteArrayEntity(RequestGenerator.login(userName, password).getBytes("UTF-8")));
            HttpResponse response = HttpClientBuilder.create().build().execute(post);
            int responseCode = response.getStatusLine().getStatusCode();

The corresponding Apex code is:

HttpResponse res = new HttpResponse();
Http http = new Http();
req.setMethod('POST');
req.setEndpoint(url);
req.setHeader('Content-Type', 'application/xml');
String xmlRequest = ReqGenerator.login(userName, password);    
req.setBody(xmlRequest);
res = http.send(req);                
Integer statusCode = res.getStatusCode();

I get a response from a server that is quite different from the Java's version.

<authResp token="adfafaf" username="adfafd"/>

Apex's version response:

<authResp />

It seems that something is wrong with the request in Apex. What I seem to miss is the setEntity() method's alternative in Apex. Is this what I'm missing?

  • Does that add parameters? Headers? Both? Neither? – Adrian Larson Jun 19 '15 at 19:19
  • setEntity does set the requestXML in bytes. Java Doc – dmachop Jun 19 '15 at 19:30
0

What I've seen in the past is something like below:

final String HEADER_TOKEN = 'Authorization';
String token = 'Basic ' + EncodingUtil.base64Encode(
    Blob.valueOf(callout.Username__c + ':' + callout.Password__c)
);
request.setHeader(HEADER_TOKEN, token);
| improve this answer | |
  • This is what I do after logging in. Currently, the login request requires sending xml and then getting response. – dmachop Jun 19 '15 at 19:31
0

Changed the header to 'Application/xml'. I have read that the header values are case insensitive too. Guess that this is due to incorrect implementation at the server side.

The answer for Java's alternative to HttpPost.setEntity(Bytes) alternative is HttpRequest.setBody(String). It did not cause any issue. Another way is to use other setBody alternatives such as HttpRequest.setBodyAsBlob(Blob.valueOf(String)) or HttpRequest.setBodyDocument(Dom.Document)).

| improve this answer | |
  • So you have solved the problem right? – Keith C Jun 19 '15 at 22:14
  • Yes. It is solved. – dmachop Jun 22 '15 at 14:54

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.