ios 异步 GET请求、POST请求
3、异步GET请求 //第一步,创建url NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do?type=focus-c"]; //第二步,创建请求 NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10]; //第三步,连接服务器 NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[connection start];
4、异步POST请求 //第一步,创建url NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do"]; //第二步,创建请求 NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10]; [request setHTTPMethod:@"POST"]; NSString *str = @"type=focus-c"; NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding]; [request setHTTPBody:data]; //第三步,连接服务器 NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self]; 5、异步请求的代理方法 //接收到服务器回应的时候调用此方法 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSHTTPURLResponse *res = (NSHTTPURLResponse *)response; NSLog(@"%@",[res allHeaderFields]); self.receiveData = [NSMutableData data]; } //接收到服务器传输数据的时候调用,此方法根据数据大小执行若干次 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self.receiveData appendData:data]; } //数据传完之后调用此方法 -(void)connectionDidFinishLoading:(NSURLConnection *)connection { NSString *receiveStr = [[NSString alloc]initWithData:self.receiveData encoding:NSUTF8StringEncoding]; NSLog(@"%@",receiveStr); } //网络请求过程中,出现任何错误(断网,连接超时等)会进入此方法 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"%@",[error localizedDescription]);
相关推荐
knightwatch 2020-07-19
Guanjs0 2020-11-09
wmsjlihuan 2020-09-15
shishengsoft 2020-09-15
poplpsure 2020-08-17
CyborgLin 2020-08-15
Richardxx 2020-07-26
sunnyhappy0 2020-07-26
wcqwcq 2020-07-04
chichichi0 2020-06-16
YAruli 2020-06-13
JF0 2020-06-13
84423067 2020-06-12
心丨悦 2020-06-11
zkwgpp 2020-06-04
stoneechogx 2020-06-04
litterfrog 2020-05-30
today0 2020-05-26