ios 网络请求基础
2012-07-20 00:33
453 查看
一、简单的get请求
网络编程是我们经常遇到的,在IPhone中,SDK提供了良好的接口,主要使用的类有 NSURL,NSMutableURLRequest,NSURLConnection等等。一般情况下建议使用异步接收数据的方式来请求网络连接,这种网络连接分为两步,第一步是新建NSURLConnection对象后,直接调用它的start方法来连接网络。第二步是使用delegate方式来接收数据,这里给一个常用的写法:
网络请求部分:
接收数据部分,接收到的数据主要是在这里处理
二、Post请求
进行post请求,主要是设置好NSMutableURLRequest对象,在get请求中,我们都使用了默认的,实际这些request内容都可以设置的。设置好后,其它与get方式同:
网络编程是我们经常遇到的,在IPhone中,SDK提供了良好的接口,主要使用的类有 NSURL,NSMutableURLRequest,NSURLConnection等等。一般情况下建议使用异步接收数据的方式来请求网络连接,这种网络连接分为两步,第一步是新建NSURLConnection对象后,直接调用它的start方法来连接网络。第二步是使用delegate方式来接收数据,这里给一个常用的写法:
网络请求部分:
NSString *urlString = [NSString stringWithFormat:@"http://www.voland.com.cn:8080/weather/weatherServlet?city=%@",kcityID]; NSURL *url = [NSURL URLWithString:urlString]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; NSURLConnection *aUrlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:true]; self.urlConnection = aUrlConnection;//这里的urlConnection在头文件中定义的变量 [self.urlConnection start];//开始连接网络 [aUrlConnection release]; [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
接收数据部分,接收到的数据主要是在这里处理
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@"接收完响应:%@",response); } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { NSLog(@"接收完数据:"); } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"数据接收错误:%@",error); } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSLog(@"连接完成:%@",connection); [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; }
二、Post请求
进行post请求,主要是设置好NSMutableURLRequest对象,在get请求中,我们都使用了默认的,实际这些request内容都可以设置的。设置好后,其它与get方式同:
NSString *content=[[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; [request setHTTPBody: content]; [request setHTTPMethod: @"POST"]; [request setValue:@"Close" forHTTPHeaderField:@"Connection"]; [request setValue:@"www.voland.com.cn" forHTTPHeaderField:@"Host"]; [request setValue:[NSString stirngWithFormat@"%d",[content length]] forHTTPHeaderField:@"Content-Length"];
相关文章推荐
- iOS基础之网络请求相关
- iOS NSURLConnection基础网络请求封装
- iOS基础网络教程-Swift版本: 2.使用UIWebView请求数据
- IOS开发之—— 在AFN基础上进行的网络请求的封装
- iOS基础8:自定义MyData/自定义SQLite用于网络判断,版本判断,图片缓存处理,下载或者上传的GET或POST请求,加密手段,.数据解析
- iOS基础知识:Objective-C 之 网络请求
- 【iOS基础】iOS 网络请求
- iOS开发总结之block回调以AFN为基础封装的网络请求操作类
- IOS--网络请求基础
- iOS网络基础--发送同步、异步请求
- iOS基础——网络请求之NSURLConnection、NSURLSessionDataTask
- iOS的网络基础
- iOS面试题 网络请求(一)
- 转载:iOS开发零基础教程之AFNetWorking POST 队列请求
- iOS webSocket 和 网络 基础知识
- iOS_UI_网络数据请求
- iOS基础 - 第三方网络框架
- iOS——封装网络请求
- iOS网络请求简单封装
- iOS网络请求----AFNetWork库的理解(1)