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);
}