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. }
原文地址:https://www.cnblogs.com/wanghuaijun/p/5349095.html