- #define CURRENT_SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
- #define CURRENT_SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height - 64)
- #define BUTTON_WIDTH 80
- #define BUTTON_HEIGHT 40
-
- @interface ViewController ()
- //GET 请求
- @property(nonatomic,strong) UIButton *getButton;
- //POST 请求
- @property(nonatomic,strong) UIButton *postButton;
- @end
-
- @implementation ViewController
- - (void)viewDidLoad {
- [super viewDidLoad];
-
- _getButton = [[UIButton alloc] initWithFrame:CGRectMake(CURRENT_SCREEN_WIDTH/2 - BUTTON_WIDTH/2,
- CURRENT_SCREEN_HEIGHT/2 - BUTTON_HEIGHT,
- BUTTON_WIDTH,
- BUTTON_HEIGHT)];
- [_getButton setTitle:@"GET 请求" forState:UIControlStateNormal];
- [_getButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
- [_getButton addTarget:self
- action:@selector(getClick)
- forControlEvents:UIControlEventTouchUpInside];
- [self.view addSubview:_getButton];
-
- _postButton = [[UIButton alloc] initWithFrame:CGRectMake(CURRENT_SCREEN_WIDTH/2 - BUTTON_WIDTH/2,
- _getButton.frame.origin.y + _getButton.frame.size.height + 60,
- BUTTON_WIDTH,
- BUTTON_HEIGHT)];
- [_postButton setTitle:@"POST 请求" forState:UIControlStateNormal];
- [_postButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
- [_postButton addTarget:self
- action:@selector(postClick)
- forControlEvents:UIControlEventTouchUpInside];
- [self.view addSubview:_postButton];
- }
- /* get 请求 */
- -(void)getClick{
- //请求 URL
- NSString* urlStr = [NSString stringWithFormat:@"https://m.che168.com/beijing/?pvareaid=%d",110100];
- //封装成 NSURL
- NSURL* url = [NSURL URLWithString:urlStr];
- //初始化 请求对象
- NSURLRequest* request = [[NSURLRequest alloc] initWithURL:url];
- //也可以这样初始化对象
- //NSURLRequest* request = [NSURLRequest requestWithURL:url];
-
- //发送请求 默认为 GET 请求
- //1 、获得会话对象
- NSURLSession *session = [NSURLSession sharedSession];
- // 2、第一个参数:请求对象
- // 第二个参数:completionHandler回调(请求完成【成功|失败】的回调)
- // data:响应体信息(期望的数据)
- // response:响应头信息,主要是对服务器端的描述
- // error:错误信息,如果请求失败,则error有值
- NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
- if(!error){
- NSLog(@"请求加载成功。。。");
- //说明:(此处返回的数据是JSON格式的,因此使用NSJSONSerialization进行反序列化处理)
- // NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
- //如果是字符串则直接取出
- NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
- NSLog(@"GET 请求返回的结果是:%@",[str substringToIndex: 300]);
- }
- }];
- //执行任务
- [dataTask resume];
-
- /* ------------ ios9 之前请求方法,之后改成 NSURLSession 请求 --------------
- [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
- if(!connectionError){
- NSLog(@"加载成功。。。");
- NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
- NSLog(@"加载的内容是:%@",[str substringToIndex:200]);
- }else{
- NSLog(@"加载失败");
- }
- }];
- */
- }
- /* POST 请求 */
- -(void)postClick{
- NSString *urlStr = [NSString stringWithFormat:@"https://m.che168.com/"];
- //转码
- // stringByAddingPercentEscapesUsingEncoding 只对 `#%^{}[]|\"<> 加空格共14个字符编码,不包括”&?”等符号), ios9将淘汰
- // ios9 以后要换成 stringByAddingPercentEncodingWithAllowedCharacters 这个方法进行转码
- urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[[NSCharacterSet characterSetWithCharactersInString:@"?!@#$^&%*+,:;='\"`<>()[]{}/\\| "] invertedSet]];
- NSURL *url = [NSURL URLWithString:urlStr];
-
- //创建会话对象
- NSURLSession *session = [NSURLSession sharedSession];
-
- //创建请求对象
- NSMutableURLRequest *request =[[NSMutableURLRequest alloc] initWithURL:url];
- [request setHTTPMethod:@"POST"];
- [request setHTTPBody:[@"a=1&b=2&c=3&type=json" dataUsingEncoding:NSUTF8StringEncoding]];
-
- //根据会话对象创建一个 Task(发送请求)
- NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
- if(!error){
- //8.解析数据
- // NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
- // NSLog(@"%@",dict);
- NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
- NSLog(@"POST 加载的内容是:%@",[str substringToIndex:200]);
- }else{
- NSLog(@"请求发生错误:%@", [error description]);
- }
- }];
- [dataTask resume]; //执行任务
- }