在GET方法中将Json值作为参数发送时不支持的URL

时间:2015-04-02 04:42:35

标签: ios json xcode6

Code:
     arrValues = [[NSMutableArray alloc]initWithObjects:@"Chennai", nil];
            arrKeys = [[NSMutableArray alloc]initWithObjects:@"loc", nil];
            dicValue = [NSDictionary dictionaryWithObjects:arrValues forKeys:arrKeys];
             NSString *strMethodName = @"agentuserlist";

            strUrlName = [NSString stringWithFormat:@"%@%@?filters=%@",appDelegate.strURL, strMethodName, dicValue];
            //strUrlName = [strUrlName stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];


        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:strUrlName] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:250.0];
        [request setHTTPMethod:@"GET"];
        [request setHTTPShouldHandleCookies:YES];

        [request setValue:@"zyt45HuJ70oPpWl7" forHTTPHeaderField:@"Authorization"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

        NSError *error;
        NSURLResponse *response;
        NSData *received = [NSURLConnection sendSynchronousRequest:request
                                                 returningResponse:&response error:&error];
        NSLog(@"error:%@", error);

        NSString *strResponse = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
        NSLog(@"response :%@", strResponse);

我尝试通过get方法发送json参数。它给出的错误为"unsupported url(-1002)"

当我与Postman核实时,网址正常。我无法找出问题所在。

我哪里出错?

1 个答案:

答案 0 :(得分:3)

我认为问题在于如何对NSDictionary中的NSURL进行编码。

您可能希望自己的网址如下所示:http://my domain.com/agentuserlist?loc=Chennai。但NSDictionaryNSURL的原始编码不会产生此结果。

您可以按照接受的答案 从这个问题中了解如何将NSDictionary转换为常规的URL参数列表(正确编码字典值:不要忘记stringByAddingPercentEscapeUsingEncoding部分):{{3 }}