//
// ViewController.m
// 050_NSURLConnetion
//
// Created by wangmutian on 2017/10/4.
// Copyright © 2017年 wangmutian. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
-(void) createurlconn{
UIButton* btn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame=CGRectMake(100, 100, 80, 40);
[btn setTitle:@"链接数据" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(prebtn) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
-(void)prebtn{
NSLog(@"HEHE");
//定义一个字符串
NSString* nstr=@"http://www.baidu.com";
//将字符串转换成地址链接url
NSURL* url=[NSURL URLWithString:nstr];
//定义一个链接请求对象
NSURLRequest* request=[NSURLRequest requestWithURL:url];
//创建一个网络连接对象
_connect = [NSURLConnection connectionWithRequest:request delegate:self];
_data=[[NSMutableData alloc] init];
}
//处理错误信息的代理协议
//如果有任何链接错误,调用此协议,进行错误打印查看
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"看这里error=%@",error);
}
//处理服务器返回的响应码
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//将响应码转换为http响应码
NSHTTPURLResponse* res=(NSHTTPURLResponse*) response;
if(res.statusCode==200){
NSLog(@"链接成功!");
}else{
NSLog(@"我把值浓出来了%@",res.statusCode);
}
}
//接收服务器回传的数据时调用
-(void)connection:(NSURLConnection *)connection didReceiveData:(nonnull NSData *)data
{
//
[_data appendData:data];
}
//
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//将二进制数据转换成字符串数据
NSString* str=[[NSString alloc] initWithData:_data encoding:NSUTF8StringEncoding];
NSLog(@"JSON=%@",str);
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self createurlconn];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end