iOS-Post异步-网络请求-网络数据请求
//
// ViewController.m
// Post异步-网络请求
//
// Created by YIem on 16/3/1.
// Copyright © 2016年 YIem. All rights reserved.
//
import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
(void)viewDidLoad {
[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.view.backgroundColor = [UIColor whiteColor]; UIButton *postButton = [UIButton buttonWithType:UIButtonTypeSystem]; postButton.frame = CGRectMake(100, 100, 100, 100); [postButton setTitle:@"Post异步网络请求" forState:UIControlStateNormal]; [postButton addTarget:self action:@selector(postAction) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:postButton];
}
(void)postAction
{// 网址 NSString *urlStr = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"; // 转码 NSString *urlEncode = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; NSURL *url = [NSURL URLWithString:urlEncode]; // 请求(设置时间) NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:50]; // 添加Body体 // 设置post模式 request.HTTPMethod = @"POST"; NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213"; // 将网址转为二进制流 NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding]; // 将二进制流添进请求 request.HTTPBody = bodyData; // 配置(默认配置) NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; // 创建请求任务 NSURLSessionDataTask *postTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; NSLog(@"--%@", dic); }];
// 开始任务
[postTask resume];
}
(void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.
}
@end