2016-06-21 1 views
0

クエリ項目を追加すると、NSURLComponentsは%2Bを+に変更し、%7Bは変更しません。私の理解から、「+」と「{'の両方をデコードすると、なぜそのうちの1つをデコードするのでしょうか?NSURLComponentsは新しいクエリの追加時に%2Bを+に変更します。項目

NSString *urlString = @"http://www.example.com?a=%7B1%2B2%7D"; 
    NSURLComponents *components = [NSURLComponents componentsWithString:urlString]; 
    NSLog(@"%@",components); 
    // <NSURLComponents 0x7ffc42c19d40> {scheme = http, user = (null), password = (null), host = www.example.com, 
    // port = (null), path = , query = a=%7B1%2B2%7D, fragment = (null)} 
    NSURLQueryItem *queryItem = [NSURLQueryItem queryItemWithName:@"hl" value:@"en-us"]; 
    components.queryItems = [components.queryItems arrayByAddingObject:queryItem]; 
    NSLog(@"%@",components); 
    // <NSURLComponents 0x7ffc42c19d40> {scheme = http, user = (null), password = (null), host = www.example.com, 
    // port = (null), path = , query = a=%7B1+2%7D&hl=en-us, fragment = (null)} 
+0

これは実際には既存の問題であり、これはdownvotesなぜ、私は知らないのですか? – ooops

答えて

0

'+'文字は、クエリコンポーネントでは正当であるため、パーセントエンコードする必要はありません。

一部のシステムでは、スペースとして '+'を使用し、プラス文字をパーセントでエンコードする必要があります。しかし、そのような2段階のエンコード(プラス記号を%2Bに変換してからスペースをプラス記号に変換する)は、エンコードの問題につながりやすいため、エラーが発生しやすくなります。また、URLが正規化されている場合(URLの構文正規化には、不要なパーセントエンコーディングがすべて削除されています - rfc3986のセクション6.2.2.2を参照してください)。

コードが話しているサーバーのためにその動作が必要な場合は、その余分な変換を自分で処理します。ここでは、両方の方法を行うために必要なものを示したコードの抜粋です:

NSURLComponents components = [[NSURLComponents alloc] init]; 
NSArray items = [NSArray arrayWithObjects:[NSURLQueryItem queryItemWithName:@"name" value:@"Value +"], nil]; 
[components setQueryItems:items]; 
NSLog(@"URL queryItems: %@", [components queryItems]); 
NSLog(@"URL string before: %@", [components string]); 
// Replace all "+" in the percentEncodedQuery with "%2B" (a percent-encoded +) and then replace all "%20" (a percent-encoded space) with "+" 
components.percentEncodedQuery = [[components.percentEncodedQuery stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"] stringByReplacingOccurrencesOfString:@"%20" withString:@"+"]; 
NSLog(@"URL string after: %@", [components string]); 
// This is the reverse if you receive a URL with a query in that form and want to parse it with queryItems 
components.percentEncodedQuery = [[components.percentEncodedQuery stringByReplacingOccurrencesOfString:@"+" withString:@"%20"] stringByReplacingOccurrencesOfString:@"%2B" withString:@"+"]; 
NSLog(@"URL string back: %@", [components string]); 
NSLog(@"URL queryItems: %@", [components queryItems]); 

出力は次のとおりです。

URL queryItems: (" {name = name, value = Value +}") 
URL string before: ?name=Value%20+ 
URL string after: ?name=Value+%2B 
URL string back: ?name=Value%20+ 
URL queryItems: (" {name = name, value = Value +}") 
関連する問題