iOS传输Json数据(纯Json)到服务器

这里写图片描述
发送Json数据(纯Json)给服务器:
必要条件:
(1):使用post请求。
(2):设置请求头为(“application/json”)。
(3):设置请求体。(要传输的Json字串)。

//上传json字串
- (void)postJson{
    NSURL * url = [NSURL URLWithString:@"http://10.66.66.9:8080/ZLServer/userInfo"];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方式
    request.HTTPMethod = @"POST";
    //设置请求头
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //设置请求体
    NSDictionary * jsonDict = @{
                                @"username" : @"zl",
                                @"age" : @"123"
                                };
    //需要将Json字串转化成NSData类型
    NSData * data = [NSJSONSerialization dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:nil];
    request.HTTPBody = data;
    //发送请求

    NSURLSession * session = [[NSURLSession alloc] init];

    [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

    }];
    //号外:开源的第三方库,比如ASI,AFN都可以以此种方式将Json数据传输到服务器
}

服务器端可以直接将接收到的json数据转换成model对象。
最后想说一句:策策。。。。。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值