異步POST請求解析JSON

 異步POST請求解析JSON

一、創建URL

NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/order"];
   
二、創建一個請求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
   
三、設置請求方法
request.
HTTPMethod = @"POST";
   
五、設置請求體(請求參數)
// 創建一個描述訂單信息的JSON數據
NSMutableDictionary *orderInfo = [NSMutableDictionary dictionary];
orderInfo[@"shop_id"] = @"123;
orderInfo[@"shop_name"] = @"123";
orderInfo[@"user_id"] = @"123";
// 將字典轉化成data
NSData *bodyData= [NSJSONSerialization dataWithJSONObject:orderInfo options:NSJSONWritingPrettyPrinted error:nil];
request.
HTTPBody bodyData;
   
六、設置請求頭:這次請求體的數據不再是普通的參數,而是一個JSON數據
[request
setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
   
七、發送請求
[
NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
   
if (data == nil || connectionError) return;
   
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
   
NSString *error = dict[@"error"];
   
if (error) {
         [
MBProgressHUD showError:error];
   }
else {
         
NSString *success = dict[@"success"];
         [
MBProgressHUD showSuccess:success];
   }
}];

注意:
 [NSJSONSerialization dataWithJSONObject:orderInfo options:NSJSONWritingPrettyPrinted error:nil]
將JSON轉化成二進制數據
[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
將二進制數據轉成JSON
設置請求頭:這次請求體的數據不再是普通的參數,而是一個JSON數據
[request
setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章