如何将json对象作为参数传递给webservice?

时间:2012-07-25 18:48:30

标签: iphone objective-c json nsmutableurlrequest

我正在使用一个以json对象作为参数的web服务。这是我的代码:

    -(void)createHttpHeaderRequest {

        NSString *x = @"{\"GetVehicleInventory\": {\"ApplicationArea\": {\"Sender\": {\"ComponentID\":}}}" (something like that)

        NSString *sample = [NSString stringWithFormat:@"https://trialservice.checkitout?XML_INPUT=%@",x];
 NSString * final = (NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)sampleReq, NULL, CFSTR(":/?#[]@!$&'()*+,;=\""), kCFStringEncodingUTF8);
 NSMutableRequest *request = [NSMutableREquest requestWithURL:[NSURL URLWithString:final]];
    NSURLConnection * theConnection = [[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
        if (theConnection) {
            NSLog(@"Service hit");
        }
    }

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
        NSError * error;
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        NSArray * categories = [dict objectForKey:@"category"];
        [self.delegate giveControlBackToController:categories];

    }

当我尝试NSLog示例时,它会给我一个完整的URL,粘贴到浏览器后会返回结果,但是当我在请求中调用NSLog时,它显示为null,此后没有任何反应。 控件永远不会进入NSURLConnection委托方法。

2 个答案:

答案 0 :(得分:1)

诀窍是大多数浏览器会自动转义URL,而NSURL则不会。你需要手动完成;看看CFURLCreateStringByAddingPercentEscapes函数。

答案 1 :(得分:0)

这应该是评论而不是答案,但不幸的是,您无法在评论中格式化代码。将以下方法添加到您的委托,并查看它是否被调用。如果是,请告诉我们答案是什么。

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    NSLog(@"Connection response code: %d", httpResponse.statusCode);
}