異步POST請求解析JSON

 異步POST請求解析JSON
json

1、建立URLapp

NSURL *url = [ NSURL URLWithString : @"http://localhost:8080/MJServer/order" ];
   
2、建立一個 請求
NSMutableURLRequest *request = [ NSMutableURLRequest requestWithURL :url];
   
3、設置 請求方法
request.
HTTPMethod = @"POST" ;
   
5、 設置請求體(請求參數)
// 建立一個描寫敘述訂單信息的 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 ;
   
6、 設置請求頭:此次請求體的數據再也不是普通的參數。而是一個 JSON 數據
[request
setValue : @"application/json" forHTTPHeaderField : @"Content-Type" ];
   
7、 發送請求
[
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"];
相關文章
相關標籤/搜索