How to make apex httprequest to some other server?
Can anyone explain how i can make a post request to some other server from apex controller and get the response back?
For example server url is - HTTP://xxx.xom/charge
I have to send a post request on the above URL from the apex controller and need the response back.
Assuming you want to make a post apex httprequest to the URL https://www.mysite.com/myendpoint you would do the following.
Add your domain under Remote Site Settings To send an outbound call (POST request) from Apex in salesforce, you need to add the domain to Remote Site Settings in setup. In the example above you would add https://www.mysite.com/
Create and send the request in your controller
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
req.setEndpoint('https://www.mysite.com/myendpoint');
req.setMethod('POST');
//these parts of the POST you may want to customise
req.setCompressed(false);
req.setBody('key1=value1&key2=value2');
req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
try {
res = http.send(req);} catch(System.CalloutException e) {
System.debug('Callout error: '+ e);
}
System.debug(res.getBody());
Other Notes
In my example above I am simulating a form post, which is why I'm not using compression (setCompressed is set to false) and using the form content type (application/x-www-form-urlencoded). If you're doing something else, such as working with a Rest API or a SOAP API, you'll want to customise this area of the code to fit your needs. The above example doesn't include any code for authentication, if your request needs this you will need to add this in. If you're calling this code from an Apex trigger, you'll want to add @future (callout=true) to the method call so it runs asynchronously.
Reference Information
This is one of the areas of salesforce with the best documentation. As you start to explore outbound requests I suggest you read up on the following:
Apex Web Services and Callouts
- HTTP Request Class
- HTTP Response Class