How to make a post request to some other server from apex controller

Can anyone explain how can i 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 above URL from apex controller and need the response back.

Thanks in advance


public class AuthCallout {

 public void basicAuthCallout(){
 HttpRequest req = new HttpRequest();

 // Specify the required user name and password to access the endpoint 

 // As well as the header and header information 

 String username = 'myname';
 String password = 'mypwd';

 Blob headerValue = Blob.valueOf(username + ':' + password);
 String authorizationHeader = 'BASIC ' +
 req.setHeader('Authorization', authorizationHeader);

 // Create a new http object to send the request object 

 // A response object is generated as a result of the request   

 Http http = new Http();
 HTTPResponse res = http.send(req);

This is the basic code.Now it depends on how you are doing Callout.If you have WSDL and converted into apex and then you may use stub classes .

Document above tells how you will parse into apex classes.

Read through the document.

Similary just use setbody method to input the body and call the request URL

public static void sendNotification(String name, String city) {

    HttpRequest req = new HttpRequest();
    HttpResponse res = new HttpResponse();
    Http http = new Http();

    req.setBody('name='+EncodingUtil.urlEncode(name, 'UTF-8')+'&city='+EncodingUtil.urlEncode(city, 'UTF-8'));
    req.setCompressed(true); // otherwise we hit a limit of 32000

    try {
        res = http.send(req);
    } catch(System.CalloutException e) {
        System.debug('Callout error: '+ e);


// run WebServiceCallout.testMe(); from Execute Anonymous to test
public static testMethod void testMe() {
    WebServiceCallout.sendNotification('My Test Customer','My City');

Source : Link , Question Author : Pramod Kumar , Answer Author : Mohith Shrivastava

Leave a Comment