2017-01-03 100 views
0

我已經爲打印一個演示代碼從Web服務的數據,如何使用NSURLSession從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

我想你不應該設置forHTTPHeaderField視頻列表。將其設置爲HTTPBody –

+0

如何設置它? @Dheeraj – user7018875

+0

你在POSTMan中傳遞的參數是什麼? –

回答

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

@ user7018875只需複製並過去此代碼並檢查它即可。 –

+0

非常感謝buddyyyyy .....非常感謝你 – user7018875

+0

工作精細.... – user7018875