详解iOS通过ASIHTTPRequest提交JSON数据

2020-01-18 19:22:16刘景俊

先验知识——什么是ASIHTTPRequest?

使用iOS SDK中的HTTP网络请求API,相当的复杂,调用很繁琐,ASIHTTPRequest就是一个对CFNetwork API进行了封装,并且使用起来非常简单的一套API,用Objective-C编写,可以很好的应用在Mac OS X系统和iOS平台的应用程序中。ASIHTTPRequest适用于基本的HTTP请求,和基于REST的服务之间的交互。

上传JSON格式数据

首先给出主功能代码段,然后对代码进行详细解析:


NSDictionary *user = [[NSDictionary alloc] initWithObjectsAndKeys:@"0", @"Version", nil]; 
        if ([NSJSONSerialization isValidJSONObject:user]) 
        { 
          NSError *error; 
          NSData *jsonData = [NSJSONSerialization dataWithJSONObject:user options:NSJSONWritingPrettyPrinted error: &error]; 
          NSMutableData *tempJsonData = [NSMutableData dataWithData:jsonData]; 
          //NSLog(@"Register JSON:%@",[[NSString alloc] initWithData:tempJsonData encoding:NSUTF8StringEncoding]); 
           
          NSURL *url = [NSURL URLWithString:@"http://www.easck.com/lev_version.php"]; 
          ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 
          [request addRequestHeader:@"Content-Type" value:@"application/json; encoding=utf-8"]; 
          [request addRequestHeader:@"Accept" value:@"application/json"]; 
          [request setRequestMethod:@"POST"]; 
          [request setPostBody:tempJsonData]; 
          [request startSynchronous]; 
          NSError *error1 = [request error]; 
          if (!error1) { 
            NSString *response = [request responseString]; 
            NSLog(@"Test:%@",response); 
          } 
        } 

代码段第一行:


NSDictionary *user = [[NSDictionary alloc] initWithObjectsAndKeys:@"0", @"Version", nil]; 

构造了一个最简单的字典类型的数据,因为自iOS 5后提供把NSDictionary转换成JSON格式的API。

第二行if判断该字典数据是否可以被JSON化。


NSData *jsonData = [NSJSONSerialization dataWithJSONObject:user options:NSJSONWritingPrettyPrinted error: &error]; 

这一句就是把NSDictionary转换成JSON格式的方法,JSON格式的数据存储在NSData类型的变量中。


NSMutableData *tempJsonData = [NSMutableData dataWithData:jsonData]; 

这一句是把NSData转换成NSMutableData,原因是下面我们要利用ASIHTTPRequest发送JSON数据时,其消息体一定要以NSMutableData的格式存储。

下面一句注视掉的语句


//NSLog(@"Register JSON:%@",[[NSString alloc] initWithData:tempJsonData encoding:NSUTF8StringEncoding]); 

主要作用是记录刚才JSON格式化的数据