• iOS开发 -- 发送JSON数据给服务器


    1. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    2. {
    3. // 1.URL
    4. NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/order"];
    5. // 2.请求
    6. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    7. // 3.请求方法
    8. request.HTTPMethod = @"POST";
    9. // 4.设置请求体(请求参数)
    10. // 创建一个描述订单信息的JSON数据
    11. NSDictionary *orderInfo = @{
    12. @"shop_id" : @"1243324",
    13. @"shop_name" : @"啊哈哈哈",
    14. @"user_id" : @"899"
    15. };
    16. //把字典转换为可以传输的NSData类型
    17. NSData *json = [NSJSONSerialization dataWithJSONObject:orderInfo options:NSJSONWritingPrettyPrinted error:nil];
    18. request.HTTPBody = json;
    19. // 5.设置请求头:这次请求体的数据不再是普通的参数,而是一个JSON数据
    20. [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    21. // 6.发送请求
    22. [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    23. if (data == nil || connectionError) return;
    24. NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    25. NSString *error = dict[@"error"];
    26. if (error) {
    27. [MBProgressHUD showError:error];
    28. } else {
    29. NSString *success = dict[@"success"];
    30. [MBProgressHUD showSuccess:success];
    31. }
    32. }];
    33. }
  • 相关阅读:
    一个简单的随机数生成算法实现(C++)
    gabor 滤波的c++实现与该类得使用简介
    嵌入式软件的覆盖测试
    scanf()函数用法小结(转载)
    创建动态2维vector (C++)
    HDU 1086 You can Solve a Geometry Problem too
    计算几何多边形的重心
    HDU 1711 Number Sequence
    HDU 2602 Bone Collector
    计算几何基础篇
  • 原文地址:https://www.cnblogs.com/wanghuaijun/p/5349095.html
Copyright © 2020-2023  润新知