当我尝试解析像" care& love"这样的特殊字符时,它只显示" care","&"之后的部分。截断我怎么能让它显示完整的字符串???
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSString *postJson = [NSString stringWithFormat:@"&json=%@", jsonRequest];
NSData *requestData = [postJson dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];
答案 0 :(得分:0)
您可以使用Cocoa's built-in JSON serialization。这将排除不正确的字符串转义(这很可能是您当前代码中的问题)。
示例:
NSError* error = nil;
NSDictionary* jsonDict = @{@"json": @"EL- STR 261: HAUL & SPOT"};
NSData* requestData = [NSJSONSerialization dataWithJSONObject:jsonDict options:kNilOptions error:&error];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];
答案 1 :(得分:0)
假设我们正在谈论jsonRequest的值,你必须在将该字符串传递给postJson之前对其进行URL编码,否则&被视为参数分隔符。
json = care& love被接收服务器解释为json =“care”和love =“”。
编码该值的网址将类似于json = love%26care,并将由服务器解码为json =“love& care”
使用stringByAddingPercentEscapesUsingEncoding进行转义,请参阅:https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/stringByAddingPercentEscapesUsingEncoding: