使用带有NSURLConnection的base64字符串

时间:2015-12-18 19:26:30

标签: ios base64 nsurlconnection

我正在使用NSURLConnect调用,当我的查询字符串中有空格时,我得到了不受支持的URL。为了解决这个问题,我将字符串转换为base64,但我仍然遇到错误。如何通过NSUrlConnect成功发送base64字符串?如果这不可能,我该如何安全地发送带有空格的字符串?

NSData *convertData = [queryWS dataUsingEncoding: NSUnicodeStringEncoding];
queryWS = [convertData base64EncodedStringWithOptions:kNilOptions];

NSURLRequest *urlRequest =
[NSURLRequest requestWithURL:[NSURL URLWithString:queryWS]];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest
                                     returningResponse:&response
                                                 error:&error];
if (!error) {
  responseDictionary =
  [NSJSONSerialization JSONObjectWithData:data
                                  options:0
                                    error:&parseError];

2 个答案:

答案 0 :(得分:1)

您不希望将URL字符串转换为base64编码。你想要的是正确地转义URL中的任何特殊字符。如果您只需要支持iOS 9或更高版本,请参阅NSString stringByAddingPercentEscapesUsingEncoding:方法或NSString stringByAddingPercentEncodingWithAllowedCharacters:

答案 1 :(得分:0)

NSString *queryString = @"SOME_QUERY_STRING";
NSString *encodedQueryString = [queryString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];