您的位置:首页 > 理论基础 > 计算机网络

ios 网络请求基础

2012-07-20 00:33 453 查看
一、简单的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"];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: