post發送JSON數據(字符串、數組、字典、自定義對象)給服務器

post發送JSON數據(字符串、數組、字典、自定義對象)給服務器

觸發發送的方法

這次Demo是通過點擊屏幕觸發發送數據給服務器事件

前提需要開啓本地模擬服務器

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/post/postjson.php"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15];

    request.HTTPMethod = @"POST";

    //選擇不同類型的data發送給服務器

//    request.HTTPBody = [self jsonString];

//    request.HTTPBody = [self dictionaryData];

//    request.HTTPBody = [self arrayData];

    request.HTTPBody = [self objectData];

#pragma clang diagnostic push

#pragma clang diagnostic ignored "-Wdeprecated-declarations"

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {

        if (data == nil || connectionError != nil) {

            NSLog(@"請求數據失敗!");

            return ;

        }

//        id recive = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];

//服務器返回的時字符串

        NSString *recive = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

        NSLog(@"%@", recive);

    }];

#pragma clang diagnostic pop

}

發送JSON字符串

- (NSData *)jsonString{

NSString *string = @"{\"name\":\"zhangsan\",\"age\":\"18\"}";

NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];

return data;

}

發送字典給服務器

- (NSData *)dictionaryData{

NSDictionary *dict = @{

                      @"name":@"zhangsan",

                      @"age":@18

                      };

//通過序列化成data類型

NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];

return data;

}

發送數組給服務器

- (NSData *)arrayData{

NSArray *array = @[

                  @{@"zhangsan":@18},

                  @{@"lisi":@20}

                  ];

NSData *data =[NSJSONSerialization dataWithJSONObject:array options:0 error:NULL];

return data;

}

發送oc對象給服務器

先講對象轉換爲字典

通過系統提供的JSON解析類進行序列化

- (NSData *)objectData{

    RZPerson *person = [[RZPerson alloc]init];

    person.name = @"zhangsan";

    person.age = 20;

    //先將對象轉換爲字典類型

    NSDictionary *dict = [person dictionaryWithValuesForKeys:@[@"name",@"age"]];

    //將字典轉換爲data類型

    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];

    return data;

    }

覺得不錯請點贊支持,歡迎留言或進我的個人羣855801563領取【架構資料專題目合集90期】、【BATJTMD大廠JAVA面試真題1000+】,本羣專用於學習交流技術、分享面試機會,拒絕廣告,我也會在羣內不定期答題、探討

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章