ios 网络链接

//

//  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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值