#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
转载于:https://www.cnblogs.com/A-Nian/p/4940138.html