[SalesForce] Apex callout – POST Method

I am making a REST callout in Apex. I have to use the POST method and send the credential to login to end system in POST's body. I have tested the endpoint using POST method by using a JAVA program where I use HTTP library to set the userId and Password of the end system in the POST parameter. I am looking for the equivalent syntax in Salesforce for the Java code:

 import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

String url="http://xyz";
 HttpClient httpclient = new DefaultHttpClient();
 HttpPost httppost = new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("userID", "XXXX"));
nameValuePairs.add(new BasicNameValuePair("password", "YYYYY"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);

What is the quivalent of this in Salesforce, how can I set the parameter as above in Apex when making the callout?

I tried the below code, where I could only think of using a JSON for this:

    public class jsonWrapper {
            public String userID {get; set;}
            public String password {get; set;}
    }
    jsonWrapper wrap = new jsonWrapper();
    wrap.userID = 'XXXX';
    wrap.password = 'YYYY';
    String jsonBody = json.serialize(wrap);
    system.debug('JSON Body****' + jsonBody);
HTTP auth = new HTTP();
HTTPRequest r = new HTTPRequest();
r.setEndpoint('http://xyz');
r.setMethod('POST');   
r.setBody(jsonBody);   
HTTPResponse authresp=new HttpResponse();
authresp = auth.send(r);

But the above code gives me an error saying – {"statusCode":"1160","severity":"FATAL","statusMessage":"Required String parameter 'userID' is not present"}

Does it have to do with how I pass the parameter in Apex? Is there way I can pass the parameter same way as in the Java Code? I looked at EncodingUtil.urlEncode() is that an equivalent of Java's UrlEncodedFormEntity ?

Appreciate any inputs.

Best Answer

I am thinking below is the equivalent .We can declare the content type to be form url encoded and then simply use strings

HTTP auth = new HTTP();
String Body = 'userID=XXXX&password=YYYYY';
HTTPRequest r = new HTTPRequest();
r.setHeader('Content-Type','application/x-www-form-urlenco‌​ded')
r.setEndpoint('http://xyz');
r.setMethod('POST');   
r.setBody(Body);   
HTTPResponse authresp=new HttpResponse();
authresp = auth.send(r);
Related Topic