My NSMutableURLRequest is truncating my URL when sending the request. Any thoughts why?
For Example:
url = @"https://mywebsite.com/restapi/authorizationheader?requiredauthhttpmethod=GET&requiredauthuri=https://mywebsite.com/restapi/accounts?user=myusername";
NSMutableURLRequest *Request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: url]];
[Request setHTTPMethod:@"POST"];
[NSURLConnection sendSynchronousRequest: Request returningResponse &resp error: &error];
But the server only receives:
https://mywebsite.com/restapi/authorizationheader?requiredauthhttpmethod=GET&requiredauthuri=https://mywebsite.com/restapi/accounts?user=
Why does "myusername" not get sent?
As you discovered, you have to percent escape the reserved characters that you add as the requiredauthuri
of your request. According to RFC 3986, the characters that should be permitted unescaped are the alphanumeric characters, plus "-", ".", "_", and "~":
2.3. Unreserved Characters
Characters that are allowed in a URI but do not have a reserved purpose are called unreserved. These include uppercase and lowercase letters, decimal digits, hyphen, period, underscore, and tilde.
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
See section 2 of the aforementioned RFC 3986 for more information.
Anyway, the proper percent encoding of the URL you are adding to your query is as follows:
NSString *reqURL = @"https://mywebsite.com/restapi/accounts?user=myusername";
NSMutableCharacterSet *allowedCharacters = [NSMutableCharacterSet alphanumericCharacterSet];
[allowedCharacters addCharactersInString:@"-._~"];
NSString *encodedReqURL = [reqURL stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
You can then obviously use that encodeReqURL
as normal:
NSString *urlString = [NSString stringWithFormat:@"https://mywebsite.com/restapi/authorizationheader?requiredauthhttpmethod=GET&requiredauthuri=%@", encodedReqURL];
NSURL *url = [NSURL URLWithString:urlString];