码迷,mamicode.com
首页 > 移动开发 > 详细

[IOS:OC]使用NSURL发送网络请求实例

时间:2015-11-05 18:23:20      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

#import "ViewController.h"

@interface ViewController ()<NSURLConnectionDelegate,NSURLConnectionDataDelegate>
@property(nonatomic,strong)NSOperationQueue *queue;//在使用conn异步连接时的队列
@end

@implementation ViewController
//conn 默认是异步的  使用get请求  使用代理方法获取响应 数据以及错误
- (IBAction)get:(UIButton *)sender {
    //创建一个请求
    NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://115.29.104.29/Server.asmx/JsonDemo1"]];
    //创建连接
    NSURLConnection *conn=[NSURLConnection connectionWithRequest:request delegate:self];
    //开始连接
    [conn start];
}
- (IBAction)post:(id)sender {
    //post需要设置  使用可变的request
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://115.29.104.29/Server.asmx/JsonDemo1"]];
    [request setHTTPMethod:@"POST"];
    NSURLConnection *conn=[NSURLConnection connectionWithRequest:request delegate:self];
    [conn start];
}
- (IBAction)sync:(id)sender {
    //同步的get请求  使用conn的静态方法sendsync
    NSURLRequest *reques=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://115.29.104.29/Server.asmx/JsonDemo1"]];
    //使用参数获取返回错误以及响应
    NSURLResponse *res;
    NSError *error;
    NSData *data=[NSURLConnection sendSynchronousRequest:reques returningResponse:&res error:&error];
    if(error)
    {
        NSLog(@"error:%@",error.localizedDescription);
    }
    else{
        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
    }
}
- (IBAction)async:(id)sender {
    //异步的get请求
    NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://115.29.104.29/Server.asmx/JsonDemo1"]];
    [NSURLConnection sendAsynchronousRequest:request queue:_queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
       //block
        if(connectionError)
        {
            NSLog(@"error:%@",connectionError.localizedDescription);
        }
        else{
            NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
        }
    }];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"服务器响应");
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"error:%@",error.localizedDescription);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _queue=[[NSOperationQueue alloc]init];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end

[IOS:OC]使用NSURL发送网络请求实例

标签:

原文地址:http://www.cnblogs.com/A-Nian/p/4940138.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!