我已经制作了一个演示代码,用于打印来自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获取数据?请帮我。

在邮递员中工作良好

图片

ios - 如何使用NSURLSession从Web服务中获取数据?-LMLPHP

谢谢。

ios - 如何使用NSURLSession从Web服务中获取数据?-LMLPHP

标头

ios - 如何使用NSURLSession从Web服务中获取数据?-LMLPHP

最佳答案

请检查一下...

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];

10-07 16:06
查看更多