如何使用NSURLSession从Web服务获取数据?

时间:2017-01-03 09:47:19

标签: ios objective-c web-services

我制作了一个用于打印来自Web服务的数据的演示代码,

代码

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

    [request setURL:[NSURL URLWithString:@"http://54.149.46.64/API/video.php"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"video" forHTTPHeaderField:@"list"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];


    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
        NSLog(@"requestReply: %@", requestReply);
    }] resume];

输出

JSON_Webservices[4496:150468] requestReply: {"Status":"Fail","Message":"Please enter required fields"}

为什么我无法从WS获取数据?请帮帮我。

在邮差中工作正常

图像

enter image description here

谢谢。

enter image description here

标题

enter image description here

1 个答案:

答案 0 :(得分:3)

请检查一下......

NSURL *aUrl = [NSURL URLWithString:@"XXXX"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60.0];

    [request setHTTPMethod:@"POST"];
    NSString *postString = @"list=video";
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
        NSLog(@"requestReply: %@", requestReply);

        NSError *jsonError;
        NSData *objectData = [requestReply dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
                                                             options:NSJSONReadingMutableContainers
                                                               error:&jsonError];
        NSLog(@"requestReply: %@", json);

    }] resume];