//同步方法發送請求並獲取返回數據
NSURLResponse *response = [[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSLog(@"%@",[(NSHTTPURLResponse *)response allHeaderFields]);
NSLog(@"%d", [(NSHTTPURLResponse *)response statusCode]);
常用方法:
//異步方法發送請求下載
NSURLConnection *_asyncConnect = nil;
if(_asyncConnect == nil) {
NSURL *asyncURL = [NSURL URLWithString:@"http:// mirrors.163.com/ubuntu-releases/13.04/ubuntu-13.04- desktop-amd64.iso"];
NSURLRequest *asyncRequest = [NSURLRequest requestWithURL:asyncURL];
_asyncConnect = [[NSURLConnection alloc]initWithRequest:asyncRequest delegate:self];}
//開始請求
[_asyncConnect start];
集中常用的協議方法:
//請求連接出錯的處理方法
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@“%@: failed:%@", [[connection currentRequest] URL], error);
}
//請求連接返回的響應頭的處理方法!
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"response status code:%d",[(NSHTTPURLResponse *)response statusCode]);
NSLog(@"response expect length:%lld", [(NSHTTPURLResponse *)response expectedContentLength]);
NSLog(@"response all headfield:%@",[(NSHTTPURLResponse *)response allHeaderFields]);
}
//請求連接收到數據的處理方法,數據量大就可能會不斷調用
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",dataStr);
}
//請求連接處理完成收據收發後的處理方法
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSSLog(@"connent to %@ finished", [[connection currentRequest] URL]);
}
NSURLConnection
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.