首页 > 代码库 > 异步POST请求解析JSON

异步POST请求解析JSON

 异步POST请求解析JSON

一、创建URL

NSURL*url = [NSURLURLWithString:@"http://localhost:8080/MJServer/order"];
   
二、创建一个请求
NSMutableURLRequest*request = [NSMutableURLRequestrequestWithURL:url];
   
三、设置请求方法
request.
HTTPMethod= @"POST";
   
五、设置请求体(请求参数)
//创建一个描述订单信息的JSON数据
NSMutableDictionary*orderInfo = [NSMutableDictionarydictionary];
orderInfo[@"shop_id"] = @"123;
orderInfo[@"shop_name"] = @"123";
orderInfo[@"user_id"] = @"123";
// 将字典转化成data
NSData*bodyData= http://www.mamicode.com/[NSJSONSerializationdataWithJSONObject:orderInfooptions:NSJSONWritingPrettyPrintederror:nil];
request.
HTTPBodybodyData;
   
六、设置请求头:这次请求体的数据不再是普通的参数,而是一个JSON数据
[request
setValue:@"application/json"forHTTPHeaderField:@"Content-Type"];
   
七、发送请求
[
NSURLConnectionsendAsynchronousRequest:requestqueue:[NSOperationQueuemainQueue]completionHandler:^(NSURLResponse*response, NSData *data,NSError *connectionError) {
   
if(data =http://www.mamicode.com/= nil || connectionError)return;
   
NSDictionary*dict = [NSJSONSerializationJSONObjectWithData:dataoptions:NSJSONReadingMutableLeaveserror:nil];
   
NSString*error = dict[@"error"];
   
if(error) {
         [
MBProgressHUDshowError:error];
   }
else {
         
NSString*success = dict[@"success"];
         [
MBProgressHUDshowSuccess:success];
   }
}];

注意:
 [NSJSONSerialization dataWithJSONObject:orderInfo options:NSJSONWritingPrettyPrinted error:nil]
将JSON转化成二进制数据
[NSJSONSerializationJSONObjectWithData:dataoptions:NSJSONReadingMutableLeaveserror:nil];
将二进制数据转成JSON
设置请求头:这次请求体的数据不再是普通的参数,而是一个JSON数据
[request
setValue:@"application/json"forHTTPHeaderField:@"Content-Type"];

异步POST请求解析JSON