I'm doing a simple HTTP callout in Apex using a Named Credential with Username/Password authentication, but I'm getting a System.CalloutException: The URI is invalid.

What could be the cause here?

    String url = 'callout:NamedCredential:4326/api/Sessions.json?file=D:\Sample-Files\United Kingdom.swd';
    Http h = new Http();

    HttpRequest req = new HttpRequest();
    req.setHeader('Content-Length', '0');

    HttpResponse response;
    response = h.send(req);

I have tried using EncodingUtil.urlEncode on the URL but that doesn't help.

  • 3
    As per the documentation the URL form is "callout:My_Named_Credential/some_path". You have a second colon which looks out of place...? – Phil W Apr 19 at 16:44
  • 2
    Agreed with @PhilW. If you are trying to specify a port number and path that should be done in the named credential record. You are able to add query parameters to the endpoint after the "?" character. – Zach Apr 19 at 16:58
  • I have just tried that and I still get "URI is invalid" unfortunately :( – fred Apr 19 at 17:03

You need to escape backslashes in source code, and URI encode unsafe characters in the URI.

String url = 'callout:NamedCredential/api/Sessions.json?file='+EncodingUtil.urlEncode('D:\\Sample-Files\\United Kingdom.swd','utf-8');

As noted in the comments, you should also put the port in the named credential directly.

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.