IOS 7 利用系統自帶庫進行 POST JSON 異步訪問操做

在上篇文章中我談到了使用 ASIHTTPRequest JSONKit 等開源庫進行 POST JSON 到服務器的操做。IOS 使用 POST、GET 提交 JSON 數據到服務器因爲在後續的開發中發現了一些問題(Stack overflow)Use ASIHTTPRequest to startAsynchronous and update UITableView but failed with EXC_BAD_ACCESS通過外國友人提示:ASIHTTPRequest 已經中止維護、在 IOS 7中存在已知 bug 。同時@未解 同窗也建議我採用 AFNetworking。可是又不想學習其它的庫操做,因而嘗試使用系統自帶的庫進行 POST 操做。json

(void)PostJson{

__block NSMutableDictionary *resultsDictionary;
/*
* 這裏 __block 修飾符必需要 由於這個變量要放在 block 中使用
*/
NSDictionary *userDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"first title", @"title",@"1",@"blog_id", nil];//假設要上傳的 JSON 數據結構爲 {"title":"first title","blog_id":"1"}
if ([NSJSONSerialization isValidJSONObject:userDictionary])//判斷是否有效
{
    NSError* error;
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:userDictionary options:NSJSONWritingPrettyPrinted error: &error];//利用系統自帶 JSON 工具封裝 JSON 數據
    NSURL* url = [NSURL URLWithString:@"www.google.com"];
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
    [request setHTTPMethod:@"POST"];//設置爲 POST 
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d",[jsonData length]] forHTTPHeaderField:@"Content-length"];
    [request setHTTPBody:jsonData];//把剛纔封裝的 JSON 數據塞進去
     __block NSError *error1 = [[NSError alloc] init];

     /*
     *發起異步訪問網絡操做 並用 block 操做回調函數
     */
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse* response,NSData* data,NSError* error)
    {
        if ([data length]>0 && error == nil) {
            resultsDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error1];
            NSLog(@"resultsDictionary is %@",resultsDictionary);

        }else if ([data length]==0 && error ==nil){
            NSLog(@" 下載 data 爲空");
        }
        else if( error!=nil){
            NSLog(@" error is %@",error);

        }
    }];
        }
    }
   }

事實上,我把這三行註釋掉也是能夠的,不知道爲何,請知道去掉會有什麼影響的朋友告知我。segmentfault

[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d",[jsonData length]] forHTTPHeaderField:@"Content-length"];
相關文章
相關標籤/搜索