网络:提交 JSON 到服务器中

来源:互联网 发布:vr软件app排行榜 编辑:程序博客网 时间:2024/05/16 23:52
#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.}- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {    // NSURL    NSURL *url = [NSURL URLWithString:@"http://localhost/post/postjson.php"];    // NSURLRequest    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];    // 设置HTTP方法    [request setHTTPMethod:@"POST"];    NSDictionary *dict = @{                           @"name":@"zhangsan"                           };    /*     - Top level object is an NSArray or NSDictionary 顶级节点必须是数据或者字典     - All objects are NSString, NSNumber, NSArray, NSDictionary, or NSNull 所有对象都必须是这几个类型     - All dictionary keys are NSStrings 字典的key值必须是strng类型     - NSNumbers are not NaN or infinity     */    //nil 0x0    // null 没有 long long value方法    NSArray *jsons = @[@1,@2,[NSNull null],@"hello"];    // 如果使用数组包装了,虽然能上传,但是返回的结果并不是我们想要的字典//    NSString *json = @"{\"name\":\"zhangsan\"}";    // 验证一下,是否符合JSON格式的要求    if (![NSJSONSerialization isValidJSONObject:jsons]) {        NSLog(@"不是JSON格式");        return;    }    // 从对象转化成JSON数据    // obj 就是要转成json的对象,必须是数组或者字典    NSData *data = [NSJSONSerialization dataWithJSONObject:jsons options:0 error:NULL];    // 向服务器提交一个json    request.HTTPBody = data;    // NSURLConnection    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);        NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]);    }];}@end
0 0
原创粉丝点击