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.
userID
and not in the body of the request. You will need to contact the external vendor or refer to their docs. Did you look at the request created from in the JAVA code you posted? care to share it here. I believe you are setting URL parameter with it and not code in a body. But I could be wrongEncodingUtil.urlEncode()
only takes a string (and an encoding scheme) as a parameter, it doesn't take a list of name-value pairs, so it's not really equivalent to Java'sUrlEncodedFormEntity