iOS development--Send JSON data to the server

Source: Internet
Author: User

  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:request queue:[ Nsoperationqueue Mainqueue] Completionhandler :^ (nsurlresponse * Response, nsdata *< Span class= "PLN" >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. }

iOS development--Send JSON data to the server

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.