AFNetworking形式-與-NSURLConnection形式的網路請求

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   os   ar   使用   for   

一:NSURLConnection網路請求

NSOperationQueue *queue = [[NSOperationQueue alloc] init];// 非同步方法呼叫[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];        NSLog(@"%@", str);}];

二:AFNetworking形式網路請求

  1.方法一

// 使用AFNetworking 2.0架構的網路請求
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];manager.requestSerializer.timeoutInterval = 30;manager.responseSerializer = [AFJSONResponseSerializer serializer];manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"]; // 很多後台格式問題用此行解決,不一定必須// httpBody// NSDictionary *httpBodyParameters = @{@"http": @"body"};
// kJsonSourceURLAddress請求地址[manager GET:kJsonSourceURLAddress_1 parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {//        NSDictionary *jsonDict = (NSDictionary *)responseObject;//        [self displayWithParsedDic:jsonDict];        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"錯誤" message:[NSString stringWithFormat:@"%@", error] delegate:nil cancelButtonTitle:@"關閉" otherButtonTitles:nil, nil];        [alert show];}];

  2.方法二

NSURL *url = [NSURL URLWithString:kJsonSourceURLAddress_1];NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30];//    NSMutableURLRequest *test = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:kJsonSourceURLAddress_1 parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {//        // TODO 檔案上傳////        [formData appendPartWithFileData:<#(NSData *)#> name:<#(NSString *)#> fileName:<#(NSString *)#> mimeType:<#(NSString *)#>]//    }];//    // 網路GET請求//    NSMutableURLRequest *requestGet = [NSMutableURLRequest requestWithURL:url];//    requestGet.HTTPMethod = @"GET";//    requestGet.timeoutInterval = 30;////    // 網路POST請求//    NSMutableURLRequest *requestPost = [NSMutableURLRequest requestWithURL:url];//    requestPost.HTTPMethod = @"POST";//    requestPost.timeoutInterval = 30;//    NSData *httpBody = [kJsonSourceURLAddress_1 dataUsingEncoding:NSUTF8StringEncoding];//    NSLog(@"%@", httpBody);//    requestPost.HTTPBody = httpBody;AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]                                         initWithRequest:urlRequest];operation.responseSerializer = [AFJSONResponseSerializer serializer];// 很多後台格式問題用此行解決,不一定必須operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {//        NSLog(@"%@", responseObject);        NSDictionary *jsonDict = (NSDictionary *)responseObject;        [self displayWithParsedDic:jsonDict];        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"錯誤" message:[NSString stringWithFormat:@"%@", error] delegate:nil cancelButtonTitle:@"關閉" otherButtonTitles:nil, nil];        [alert show];}];// 上傳進度//    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {////    }];[[NSOperationQueue mainQueue] addOperation:operation];

補充:系統內建的json解析

// json資料解析成NSDictionaryNSDictionary *parseData = [NSJSONSerialization JSONObjectWithData:_jsonData options:NSJSONReadingMutableLeaves error:&error];// NSDictionary轉換成json()NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];

 

AFNetworking形式-與-NSURLConnection形式的網路請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.