Iphone中的网络请求

一、简单的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"];
原文地址:[url]http://www.voland.com.cn/httpconnection-for-iphone-in-the-network-request[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值