详谈iPhone中网络请求(转载)

(原文地址:http://mobile.51cto.com/iphone-280009.htm)

详谈iPhone网络请求是本文要介绍的内容,主要介绍了网络编程的相关内容,很详细的介绍了如何获得或者发送网络请求。不多说,我们先来看详细内容。

一、简单的get请求

网络编程是我们经常遇到的,在IPhone中,SDK提供了良好的接口,主要使用的类有NSURL,NSMutableURLRequest,NSURLConnection等等。一般情况下建议使用异步接收数据的方式来请求网络连接,这种网络连接分为两步,第一步是新建NSURLConnection对象后,直接调用它的start方法来连接网络。第二步是使用delegate方式来接收数据,这里给一个常用的写法:

网络请求部分:

1 NSString *urlString = [NSString stringWithFormat:@"http://www.voland.com.cn:8080/weather/weatherServlet?city=%@",kcityID];  
2 NSURL *url = [NSURL URLWithString:urlString];  
3 NSMutableURLRequest *request = [NSMutableURLRequest  requestWithURL:url];  
4 NSURLConnection *aUrlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:true];  
5 self.urlConnection = aUrlConnection;//这里的urlConnection在头文件中定义的变量  
6 [self.urlConnection start];//开始连接网络  
7 [aUrlConnection release];  
8 [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; 

接收数据部分,接收到的数据主要是在这里处理

 1 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response  {  
 2 NSLog(@"接收完响应:%@",response);  
 3 }  
 4 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data  {  
 5 NSLog(@"接收完数据:");  
 6 }  
 7 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error  {  
 8 NSLog(@"数据接收错误:%@",error);  
 9 }  
10 - (void)connectionDidFinishLoading:(NSURLConnection *)connection  {  
11 NSLog(@"连接完成:%@",connection);  
12 [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];  
13 } 

二、Post请求

进行post请求,主要是设置好NSMutableURLRequest对象,在get请求中,我们都使用了默认的,实际这些request内容都可以设置的。设置好后,其它与get方式同:

1 NSString *content=[[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];  
2 [request setHTTPBody: content];    
3 [request setHTTPMethod: @"POST"];    
4 [request setValue:@"Close" forHTTPHeaderField:@"Connection"];    
5 [request setValue:@"www.voland.com.cn" forHTTPHeaderField:@"Host"];    
6 [request setValue:[NSString stirngWithFormat@"%d",[content length]] forHTTPHeaderField:@"Content-Length"]; 

小结:详谈iPhone网络请求的内容介绍完了,希望本文对你有所帮助!

(原文地址:http://mobile.51cto.com/iphone-280009.htm)

posted @ 2013-03-30 13:34  bxddno1  阅读(197)  评论(0)    收藏  举报