iOS应用中发送HTTP的get请求以及HTTP异步请求的方法
作者:常思过
这篇文章主要介绍了iOS应用中发送HTTP的get请求以及HTTP异步请求的方法,代码为传统的Objective-C语言,说明都简单地融入于注释之中,需要的朋友可以参考下
Http get 请求
复制代码 代码如下:
// 组合一个搜索字符串
NSString *urlStr = [NSString stringWithFormat:@"http://www.baidu.com/s?wd=%@", @"php"];
// 字符串转化为URL
NSURL *url = [NSURL URLWithString:urlStr];
// NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
// [request setURL:url];
// [request setHTTPMethod:@"POST"];
// [request setTimeoutInterval:60];
// [request setHTTPBody:_data];
// [request setValue:@"ttt" forHTTPHeaderField:@"cookies"];
// url转化为一个请求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 状态请求
NSURLResponse *response;
// 链接一个请求
NSData *resultData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
// 返回数据转为字符串
NSData *dataString = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
NSLog(@"%@", dataString);
// 解析json吧
Http异步请求
复制代码 代码如下:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
_data = [[NSMutableData alloc] init];
// 组合一个搜索字符串
NSString *urlStr = [NSString stringWithFormat:@"http://www.baidu.com/s?wd=%@", @"php"];
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//发起请求,定义代理
[NSURLConnection connectionWithRequest:request delegate:self];
}
// 分批返回数据
- (void)connection:(NSURLConnection *) connection didReceiveData:(NSData *)data {
[_data appendData:data];
NSLog(@"%@", _data);
}
// 数据完全返回完毕
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *dataString = [[NSString alloc] initWithData:_data encoding:NSUTF8StringEncoding];
NSLog(@"%@", dataString);
}