发送POST请求
NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/demo.json"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"post";
NSString *body = @"username=123&password=123";
request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSLog(@"%@",json);
}] resume];
发送GET请求
NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/demo.json"];
[[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse *
_Nullable response, NSError * _Nullable error) {
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSLog(@"%@",json);
}] resume];
文件下载
NSURL *url = [NSURL URLWithString:@"abc.hm"];
[[[NSURLSession sharedSession] downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@",[NSThread currentThread]);
NSLog(@"%@",location);
NSString *doc = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"123.hm"];
//复制到其他位置
[[NSFileManager defaultManager] copyItemAtPath:location.path toPath:doc error:NULL];
}] resume];