使用编码加(%2B)创建NSURL

时间:2009-05-22 15:30:53

标签: iphone url html-encode

我需要在GET请求中传递带时区偏移的时间戳,例如,

  

2009-05-04T11:22:00 + 01:00

这看起来像接收PHP脚本的两个参数“2009-05-04T11:22:00”和“01:00”(我无法控制)。

NSURL不对加号进行编码,但是如果我使用字符串

进行NSURL
  

2009-05-04T11:22:00%2B01:00

我最终得到的网址包含:

  

2009-05-04T11:22:00%252B01:00

任何想法如何保存我的编码加号或只是简单地阻止NSURL编码任何东西?

7 个答案:

答案 0 :(得分:13)

对我有用的是进行UTF8转换,然后用%2B替换+号:

NSString *urlString =
    [NSString stringWithFormat:@"%@/iphone/push/create?pn[token]=%@&pn[send_at]=%@",
     kHTTPURL, appDelegate.deviceAPNToken, [dateTimeToUse description]];

urlString =
    [[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
     stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];

答案 1 :(得分:3)

字符串应该是URL编码。

这是NSString的一个类别,可以提供帮助:

<强>的NSString + Additions.h

@interface NSString (Additions)

- (NSString *)stringByURLEncoding;

<强>的NSString + Additions.m

#import "NSString+Additions.h"

@implementation NSString (Additions)

- (NSString *)stringByURLEncoding {
    return (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
                                                           (CFStringRef)self,
                                                           NULL,
                                                           (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                                                           CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
}

答案 2 :(得分:2)

对要包含在参数中的文本使用NSString的{​​{1}}方法。

顾名思义,该方法将转换返回包含接收者的url-safe版本的自动释放字符串。

答案 3 :(得分:2)

我想我也可以提供我的解决方案作为答案,因为我认为原始问题并没有很好的解决方案。

加号(+)在URL中完全有效,所以我的解决方案是将时间转换为GMT并从字符串中删除时区/ DST偏移量。我将把它作为练习让读者确定下面的 secondsFromGMT 的值,因为在我的情况下,它总是相同的,因为我只对Web服务器生成的时间戳感兴趣。

NSString *gmtWhen = [[self descriptionWithCalendarFormat:nil
                           timeZone:[NSTimeZone
                           timeZoneForSecondsFromGMT:secondsFromGMT
                     ] locale:nil] stringByReplacingOccurrencesOfString:@" +0000" withString:@""];

答案 4 :(得分:0)

使用下面的代码

对您的字符串进行编码

NSString * result =(NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)自,NULL,(CFStringRef)@&#34; +&#34;,kCFStringEncodingUTF8);

这将编码你的字符串+,这将阻止在post方法

中发布数据时用%2b替换+

答案 5 :(得分:0)

要获得编码加(%2B)(适用于所有字符),请使用CFURLCreateStringByAddingPercentEscapes作为

/**
 get parameterized url from url and query parameters.
 */
+(NSString *)getParameterizedUrl:(NSString *)url withParameters:(NSDictionary *)queryDictionary
{
    NSMutableArray *mutablePairs = [NSMutableArray array];
    for (NSString *key in queryDictionary) {
        [mutablePairs addObject:[NSString stringWithFormat:@"%@=%@", CTPercentEscapedQueryStringKeyFromStringWithEncoding(key, NSUTF8StringEncoding), CTPercentEscapedQueryStringValueFromStringWithEncoding(queryDictionary[key], NSUTF8StringEncoding)]];
    }

    return [[NSString alloc]initWithFormat:@"%@?%@",url,[mutablePairs componentsJoinedByString:@"&"]];
}

static NSString * const kCharactersToBeEscapedInQueryString = @":/?&=;+!@#$()',*";

static NSString * CTPercentEscapedQueryStringKeyFromStringWithEncoding(NSString *string, NSStringEncoding encoding) {
    static NSString * const kCharactersToLeaveUnescapedInQueryStringPairKey = @"[].";

    return (__bridge_transfer  NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, (__bridge CFStringRef)kCharactersToLeaveUnescapedInQueryStringPairKey, (__bridge CFStringRef)kCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding));
}

static NSString * CTPercentEscapedQueryStringValueFromStringWithEncoding(NSString *string, NSStringEncoding encoding) {
    return (__bridge_transfer  NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)kCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding));
}

并在您的代码中使用

NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setObject:@"2009-05-04T11:22:00+01:00" forKey:@"timestamp"];

NSString *urlString = [self getParameterizedUrl:@"http://www.example.com" withParameters:params];
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

答案 6 :(得分:0)

使用 URLComponents (Swift 3)时的解决方案:

var params = ["email": "user+ios-default@example.com", "name": "John Brown"]
var components = URLComponents(string: "http://www.example.com")!
components.path = "/login"
components.queryItems = params.map { URLQueryItem(name: $0, value: $1) }

let url_NoFix = components.url!
// http://www.example.com/login?name=John%20Brown&email=user+ios-default@example.com

let cs = CharacterSet(charactersIn: "+").inverted
let q =  components.percentEncodedQuery?.addingPercentEncoding(withAllowedCharacters: cs)
components.percentEncodedQuery = q

let url_Fixed = components.url!
// http://www.example.com/login?name=John%20Brown&email=user%2Bios-default@example.com