ios 网络编程之iPhone中的网络请求
一、简单的get请求
网络编程是我们经常遇到的,在IPhone中,SDK提供了良好的接口,主要使用的类有 NSURL,NSMutableURLRequest,NSURLConnection等等。一般情况下建议使用异步接收数据的方式来请求网络连接,这种网络连接分为两步,第一步是新建NSURLConnection对象后,直接调用它的start方法来连接网络。第二步是使用delegate方式来接收数据,这里给一个常用的写法:
网络请求部分:
1 2 3 4 5 6 7 8 |
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]; |
接收数据部分,接收到的数据主要是在这里处理
1 2 3 4 5 6 7 8 9 10 11 12 13 |
- (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方式同:
1 2 3 4 5 6 |
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"]; |