1. 程式人生 > >iOS 學習日誌 : 向伺服器傳送Json資料

iOS 學習日誌 : 向伺服器傳送Json資料

前幾天介面需要我向伺服器傳送一個Json資料,但是利用AFNetWorking中的AFHTTPSessionManager傳送到伺服器,介面接收的串一直是URL編碼過後的串,無法和安卓統一,於是換了另一種方法,利用AFHTTPSessionManager的子類AFHTTPRequestOperation設定UTF-8編碼才成功,用AFHTTPSessionManager設定UTF-8編碼是無效的,不知道其中哪個環節出了問題,斷電追到裡面,發現設定無效。

NSDictionary * dict = @{@"id":@"12312312",@"name":@"test"};
            NSData * data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error
:nil]; NSString * json = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; //字典轉Json串 為了方便,避免自己拼串出錯]] NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:[json dataUsingEncoding:NSUTF8StringEncoding]]; [request setValue:@"text/html;charset=utf-8"
forHTTPHeaderField:@"Content-Type"]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; //]] operation.responseSerializer = [AFJSONResponseSerializer serializer]; //]] [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { //成功]] } failure:^(AFHTTPRequestOperation *operation, NSError *error
) { //失敗 }]; [operation start];