6

Using apex:outputLink or URLFOR(target, id, params) is great in Visualforce. But in Apex land I always see people looping through lists using EncodingUtil.urlEncode(param, 'UTF-8').

If System.Url doesn't have a parameter parser or builder, what's the best way to do it?

11

This capability is available using the PageReference class. You can use the same mechanism to build query strings or parse the parameters out of one, without loops and a whole lotta script statements.

Parse an RFC 3986 URL query string

String query = '?password=Hunter2dog%26cat&username=user%40example.com';

System.PageReference pageReference = new System.PageReference('/' + query);
Map<String,String> parameters = pageReference.getParameters();

String password = parameters.get('password'); //Hunter2dog&cat
String username = parameters.get('username'); //user@example.com

Build an RFC 3986 URL query string

Map<String,String> parameters = new Map<String,String>{
  'password' => 'Hunter2dog&cat',
  'username' => 'user@example.com'
};

System.PageReference pageReference = new System.PageReference('');
pageReference.getParameters().putAll(parameters);

String query = pageReference.getUrl();
//?password=Hunter2dog%26cat&username=user%40example.com

http://www.ietf.org/rfc/rfc3986.txt

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.