0

Hoping someone could help with this little problem I am having, I have a cURL that works just fine, but what I need is an Salesforce APEX / Rest API / HttpRequest instead. Here is my cURL:

curl -X POST --header "Content-Type: application/json" --header "Accept: application/json" --header "Authorization: Bearer f43e0234e30ec45467065b6c1543a0d3f2" -d "{
  \"username\": \"string\",
  \"password\": \"string\"
}" "https://thingspace.verizon.com/api/m2m/v1/session/login"
2

1 Answer 1

1

A good place to start would be to look at the documentation on HttpRequest.

Most everything should map fairly intuitively from cURL.

For example...

  • POST, GET, PUT, etc... are Http methods, so use setMethod(String method)
  • you'd pass 'https://thingspace.verizon.com...' into setEndpoint(String endpoint)
  • each individual header is set by using setHeader(String key, String value), e.g. request.setHeader('Authorization', 'Bearer <token string here>')
  • POST data is sent in the body of the request, so setBody(String) is what you'd use

The actual request is sent by using the send() method of the Http class (documentation here)

About the only other gotcha that I can think of is that you can't examine the network request (because it is sent from one of Salesforce's servers), so it's a very good idea to store the HttpResponse result you get from Http.send(HttpRequest request) in a separate variable, and have logic to inspect the status code via HttpResponse.getStatus() and HttpResponse.getStatusCode().

If you don't check the response code/message, you won't have any way of determining if your callout worked, or what went wrong (if it didn't work).

1
  • HTTP auth = new HTTP(); String payload = 'username: me' + 'password: pass'; HTTPRequest r = new HTTPRequest(); r.setEndpoint('thingspace.verizon.com/api/m2m/v1/session/login'); r.setHeader('Content-Length',String.valueOf(payload.length())); r.setHeader('Authorization', 'Bearer xxxx); r.setHeader('content-type', 'application/json'); r.setBody(payload); r.setMethod('POST'); HTTPResponse authr=new HttpResponse(); authr = auth.send(r); authr.setHeader('content-type', 'application/json'); DEBUG 400 {"errorCode":"REQUEST_FAILED.UnexpectedError","errorMessage":"Bad Request"} Mar 27, 2017 at 17:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .