目前可能只是单纯的贴上了一些demo的代码,但是这些代码都是请求数据应该是最基础的使用方法吧,在项目的实际开发中可能用到系统的会非常少,一般都是采用别人非常成熟的第三方开源库来实现数据请求,目前常用的第三方网络请求.
</pre><pre name="code" class="objc">
#pragma mark -- NetWorking methods
// 分别是get的同步和异步
- (void)getHttpRequest
{
NSString *urlString = [NSString stringWithFormat:@"http://api.jiepang.com/v1/locations/search?lat=%f&lon=%f&source=100000&count=50",30.575413,104.064359];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
/*
NSError *error = nil;
// 这里是发布同步请求,同步请求会阻塞主线程,在请求未完成过程中程序是无法进行交互的
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
if (error) {
NSLog(@"request error reason '%@'",[error localizedDescription]);
}else
{
//进行数据解析,这里是json解析采用的系统自带的
id objId = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
_weatherLabel.text = objId[@"result"][@"today"][@"weather"];
NSLog(@"%@",objId);
}
*/
// 这里是通过代理来实现异步请求 需要实现其代理方法去获取数据
[NSURLConnection connectionWithRequest:request delegate:self];
}
// post异步请求
- (void)postHttpRequest
{
NSURL *url = [NSURL URLWithString:OIL_PRICE];
// 对参数进行处理
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setObject:@"5a43794d639815615b93fdfddcef3670" forKey:@"key"];
NSMutableString *mstring = [NSMutableString string];
for (NSString *key in [params allKeys]) {
[mstring appendFormat:@"%@=%@",key,params[key]];
}
// POST 请求需要可变的URLRequest
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPBody = [mstring dataUsingEncoding:NSUTF8StringEncoding]; // 请求参数进行编码
request.HTTPMethod = @"POST"; // 请求方式
request.timeoutInterval = 10;//请求超时时间
[NSURLConnection connectionWithRequest:request delegate:self];
}
</pre><pre name="code" class="objc"><pre name="code" class="objc">#pragma mark -- <NSURLConnectionDelegate>
// 请求完毕调用此方法
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error = nil;
id objID = [NSJSONSerialization JSONObjectWithData:_receiveData options:NSJSONReadingMutableLeaves error:&error];
if (error) {
NSLog(@"reciveData error reason : '%@'.",[error localizedDescription]);
}else
{
_dataSource = [objID[@"items"] mutableCopy];
[_tableView reloadData];
}
}
// 数据流接收方法
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// 接受数据
[_receiveData appendData:data];
}