1.NSURLConnection代理下载设置在本地的身骑着白马MP3
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib. self.data = [NSMutableData data]; NSString * urlString = @"http://localhost/身骑白马.mp3"; //如果接口中有中文
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL * url = [NSURL URLWithString:urlString]; NSURLRequest * request = [NSURLRequest requestWithURL:url]; NSURLConnection * connect = [NSURLConnection connectionWithRequest:request delegate:self]; //开启网络连接
[connect start];
} //服务器返回响应信息
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@"%@",response); } //接受数据(多次调用)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self.data appendData:data];
NSLog(@"%@",data); } //请求完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{ [self.data writeToFile:@"/Users/mac/Desktop/身骑白马.mp3" atomically:YES];
NSLog(@"网络请求完成"); }
2.GET请求
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; //使用get请求,获取接口 NSString * String = @"http://localhost/login.php"; //拼接参数
NSString * urlString = [NSString stringWithFormat:@"%@?username=xubaoaichiyu&password=123456",String]; //如果有中文进行转码 urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL * url = [NSURL URLWithString:urlString]; NSURLRequest * request = [[NSURLRequest alloc]initWithURL:url cachePolicy: timeoutInterval:]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { NSString * string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",string); }]; } @end
3.POST请求
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; //使用post请求
//获取接口
NSString * string = @"http://localhost/login.php"; //中文转码
string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL * url = [NSURL URLWithString:string]; //可变请求
NSMutableURLRequest * requst = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy: timeoutInterval:]; //设置传输方式 requst.HTTPMethod = @"POST"; NSString * bodyString = [NSString stringWithFormat:@"username=xubaoaichiyu&password=123456"]; //设置请求体 requst.HTTPBody = [bodyString dataUsingEncoding:NSUTF8StringEncoding]; [NSURLConnection sendAsynchronousRequest:requst queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { NSString * string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",string); }]; }