Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

up vote 7 down vote accepted

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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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