4

In order to make a @future(callout=true) call, I'm serializing an HTTPRequest object in order to send it to the @future method accepting a String jsonHttpRequest parameter.

Instance Method

HttpRequest request = new HttpRequest();

request.setEndpoint(someUrl);
// ... continue populating request

sendAsyncRequest(JSON.serialize(request));

Future Method

@future(callout=true)
private static void sendAsyncRequest(String jsonHttpRequest) {
    HttpResponse response = new Http().send((HttpRequest)JSON.deserialize(jsonHttpRequest, HttpRequest.class));
}

But this code is giving me the following error:

System.JSONException: Apex Type unsupported in JSON: System.HttpRequest

Using JSON.deserializeStrict() and JSON.deserializeUntyped() hasn't worked for me either.

Any ideas here? I'm open to other approaches (thought about Queueable but @future is a more natural fit for the current use case)

8

There are certain classes that are not serializable, and HttpRequest is one of them. I can't seem to find supporting documentation, but from what I recall this is a pretty common constraint in other languages too.

The solution here is to store the configuration for your callout in something like a Map<String, String> or a custom configuration wrapper class, serialize that, and then use it to create your HttpRequest inside of your async method of choice.

If you go the route of the configuration wrapper class, you could include a method that returns an HttpRequest to save you the trouble of doing it elsewhere.

| improve this answer | |
  • I know, this is a picky point, but what you describe is not strictly a wrapper class since it doesn't (and cannot) hold the HttpRequest as an attribute. Instead it would be an Apex class extracting its state from an HttpRequest on construction (for example) and providing a method to reconstruct an HttpRequest from its state. (Re-reading, you do say "configuration wrapper" but still I don't think it's a good term.) – Phil W Jul 8 '19 at 6:38
  • Any ideas where list of given classes can be found? – kurunve Jul 8 '19 at 8:38
  • Thanks @DerekF, this makes sense. I was writing the code way too late at night and realized this morning that I could just use a few String parameters to accomplish what I needed as well – Brian Miller Jul 8 '19 at 11:42
  • 1
    @kurunve I don't think such a list exists. If it does, I haven't been able to find it. A few items like HttpResponse and System.Savepoint are known to be non-serializable, but beyond that it seems the only way to figure this out would be to go through classes one by one to test their serializability. – Derek F Jul 8 '19 at 14:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.