我的NSMutableURLRequest在发送请求时截断了我的URL。有什么想法吗?
例如:
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];
但是服务器只接收:
https://mywebsite.com/restapi/authorizationheader?requiredauthhttpmethod=GET&requiredauthuri=https://mywebsite.com/restapi/accounts?user=
为什么“myusername”没有被发送?
答案 0 :(得分:1)
NSString *userName = @"your username";
NSString *postStr = [NSString stringWithFormat:@"%@", userName];
[request setHTTPBody:[postStr dataUsingEncoding:NSUTF8StringEncoding]];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
答案 1 :(得分:1)
正如您所发现的那样,您必须百分之百地转义您添加为请求的requiredauthuri
的保留字符。根据{{3}},应该允许未转义的字符是字母数字字符,加上" - ","。"," _",和"〜":
2.3。未保留的字符
URI中允许但没有保留目的的字符称为unreserved。这些包括大写和小写字母,十进制数字,连字符,句点,下划线和波浪号。
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
有关详细信息,请参阅上述RFC 3986的第2部分。
无论如何,您要添加到查询中的URL的正确百分比编码如下:
NSString *reqURL = @"https://mywebsite.com/restapi/accounts?user=myusername";
NSMutableCharacterSet *allowedCharacters = [NSMutableCharacterSet alphanumericCharacterSet];
[allowedCharacters addCharactersInString:@"-._~"];
NSString *encodedReqURL = [reqURL stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
然后你可以显然正常使用encodeReqURL
:
NSString *urlString = [NSString stringWithFormat:@"https://mywebsite.com/restapi/authorizationheader?requiredauthhttpmethod=GET&requiredauthuri=%@", encodedReqURL];
NSURL *url = [NSURL URLWithString:urlString];
答案 2 :(得分:0)
事实证明问题确实与编码有关。虽然我不是100%导致问题的原因,但我知道在我的NSMutableURLRequest和服务器接收之间的某个时刻(可能是因为NSURLConnection sendSynchronousRequest如何工作),用户名被截断了。我怀疑这是因为我有两个查询字符串。
解决方案是允许使用“?”进行编码字符。强>
解决方案代码:
authURLBase = @"https://mywebsite.com/restapi/authorizationheader?requiredauthhttpmethod=GET&requiredauthuri=";
reqURL = @"https://mywebsite.com/restapi/accounts?user=myusername";
authURL = [authURLBase stringByAppendingString:[reqURL stringByAddingPercentEncodingWithAllowedCharacters:[NSMutableCharacterSet characterSetWithCharactersInString:@"?"]]];