HTTP 请求的常见方法
GET
所有参数拼接在URL后面,并且参数之间用&隔开
- 比如http://192.168.1.123?name=123&pwd=123
传递了两个参数给服务器
- name参数 :123
- pwd 参数 :123
没有请求体
一般用来查询数据
POST
- 所有参数都在‘请求体’
- 一般用来修改,增加,删除数据
HTTP 请求的常见方法
使用NSURLConnection发送HTTP请求
//1、创建URL,访问网络资源的唯一地址
NSURL * url = [NSURL URLWithString:@"http://192.168.1.123/demo.json"];
//2、创建网络请求
/*
cachePolicy 缓存策略
NSURLRequestUseProtocolCachePolicy = 0, //自动缓存策略
NSURLRequestReloadIgnoringLocalCacheData = 1, //每次都请求网络,无论本地是否存在缓存
NSURLRequestReturnCacheDataElseLoad = 2,//如果有缓存返回缓存,没有就加载网络
NSURLRequestReturnCacheDataDontLoad = 3,//如果有缓存返回缓存,没有也不加载网络
timeoutInterval 请求超时 默认超时时间是60 一般设置 10 - 20s
*/
// NSURLRequest * request = [NSURLRequest requestWithURL:url];
NSURLRequest * request = [NSURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:15];
//3、建立连接
//sendAsynchronousRequest 建立异步网络连接
//queue 可以传主队列,或全局队列
//[NSOperationQueue mainQueue] 不用调到主队列直接更新
//[[NSOperationQueue alloc] init] 则需要调回主线程更新UI
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//response 服务器响应信息,一般下载时有用
//data 服务器返回的数据
//connectionError 网络请求错误
//服务器与客户端是以二进制流通讯的
// NSLog(@"%@",data);
//
// [data writeToFile:@"/Users/dahuan/Desktop/test" atomically:YES];
NSLog(@"%@",[NSThread currentThread]);
// if (connectionError) {
//
// NSLog(@"错误信息:%@",connectionError);
//
// } else {
//
// NSLog(@"响应信息:%@",response);
//
// NSString * string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//
// NSLog(@"%@",string);
//
// [self.webView loadHTMLString:string baseURL:nil];
// }
//
// [[NSOperationQueue mainQueue] addOperationWithBlock:^{
// //更新UI
// }];
- 同步网络请求
- 源代码
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSURL * url = [NSURL URLWithString:@"http://192.168.1.123/demo.json"];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
//同步网络请求
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString * string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",string);
NSLog(@"%@",response);
}
- 异步网络
- -
@interface ViewController ()<NSURLConnectionDataDelegate>
@property (nonatomic, strong) NSMutableData * data;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.data = [NSMutableData data];
NSString * urlString = @"http://192.168.1.123/把悲伤留给自己.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/dahuan/Desktop/aaaaa.mp3" atomically:YES];
NSLog(@"网络请求完成");
}
- NSURLConnectionURLDelegate
- -
#import "ViewController.h"
@interface ViewController ()<NSURLConnectionDataDelegate>
@property (nonatomic, strong) NSMutableData * data;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.data = [NSMutableData data];
NSString * urlString = @"http://192.168.1.123/把悲伤留给自己.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/dahuan/Desktop/aaaaa.mp3" atomically:YES];
NSLog(@"网络请求完成");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#import "ViewController.h"
@interface ViewController ()<NSURLConnectionDataDelegate>
@property (nonatomic, strong) NSMutableData * data;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.data = [NSMutableData data];
NSString * urlString = @"http://192.168.1.123/把悲伤留给自己.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/dahuan/Desktop/aaaaa.mp3" atomically:YES];
NSLog(@"网络请求完成");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
网络请求默认是get
网络请求有很多种:GET查 POST改 PUT增 DELETE删 HEAD
在平时开发中主要用的 是 get 和 post.
get 获得数据 (获取用户信息)
get 请求是没有长度限制的,真正的长度限制是浏览器做的,限制长度一般2k
get 请求是有缓存的,get 有幂等的算法
get http://localhost/login.php?username=dahuan&password=123
请求参数暴露在url里
get请求参数格式:
?后是请求参数
参数名 = 参数值
& 连接两个参数的
post 添加,修改数据 (上传或修改用户信息)
post 请求是没有缓存的
http://localhost/login.php
post 也没有长度限制,一般控制2M以内
post 请求参数不会暴漏在外面 ,不会暴漏敏感信息
请求是有:请求头header,请求体boby(post参数是放在请求体里的)
*/
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// http://192.168.1.123/login.php?username=dahuan&password=123
NSString * username = @"dahuan";
NSString * pwd = @"123";
//使用GET请求
//获取接口
NSString * urlString = @"http://127.0.0.1/login.php";
//中文转码
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL * url = [NSURL URLWithString:urlString];
//可变请求
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:10];
//设置传输方式
request.HTTPMethod = @"POST";
NSString * bodyString = [NSString stringWithFormat:@"username=%@&password=%@",username,pwd];
//设置请求体
request.HTTPBody = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
[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);
}];
}
- (void)getRequest {
NSString * username = @"haha";
NSString * pwd = @"123";
//使用GET请求
//获取接口
NSString * urlString = @"http://192.168.1.123/login.php";
//拼接参数
urlString = [NSString stringWithFormat:@"%@?username=%@&password=%@",urlString,username,pwd];
//中文转码
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL * url = [NSURL URLWithString:urlString];
NSURLRequest * request = [NSURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:10];
[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);
}];
}
GET/POST
- 代码
-
- `
-
import “ViewController.h”
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// http://192.168.1.123/login.php?username=dahuan&password=123
NSString * username = @"dahuan";
NSString * pwd = @"123";
//使用GET请求
//获取接口
NSString * urlString = @"http://127.0.0.1/login.php";
//中文转码
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL * url = [NSURL URLWithString:urlString];
//可变请求
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:10];
//设置传输方式
request.HTTPMethod = @"POST";
NSString * bodyString = [NSString stringWithFormat:@"username=%@&password=%@",username,pwd];
//设置请求体
request.HTTPBody = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
[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);
}];
}
(void)getRequest {
NSString * username = @”haha”;
NSString * pwd = @”123”;//使用GET请求
//获取接口
NSString * urlString = @”http://192.168.1.123/login.php“;//拼接参数
urlString = [NSString stringWithFormat:@”%@?username=%@&password=%@”,urlString,username,pwd];//中文转码
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];NSURL * url = [NSURL URLWithString:urlString];
NSURLRequest * request = [NSURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:10];
[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);
}];
}`
static NSString * identifier = @"cellID";
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) NSArray * dataList;
@end
@implementation ViewController
- (UITableView *)tableView {
if (!_tableView) {
_tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
_tableView.dataSource = self;
_tableView.delegate = self;
[_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:identifier];
}
return _tableView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.dataList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
cell.textLabel.text = [self.dataList[indexPath.row] province_name];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// SXTCity * city = self.dataList[indexPath.row];
NSDictionary * dict = @{@"city":@"北京",
@"province":@"地球"};
//字典转JSON
// NSData * data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
NSData * data = [dict JSONData];
NSString * string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",string);
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
/*
JSON是一个特殊的字符串,用于数据传输
JSON 用于90%以上的app
http://192.168.1.123/city.json
JSON在线格式化
*/
[self.view addSubview:self.tableView];
[self loadData];
}
- (void)loadData {
NSURL * url = [NSURL URLWithString:@"http://192.168.1.123/city.json"];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (connectionError) {
NSLog(@"请求错误:%@",connectionError);
} else {
//json 数据解析
// NSJSONSerialization iOS6之后出现的,json解析可能出错
// 古老的JSON SBJSON JSONKit
//Data 要解析的数据
//options
// NSJSONReadingMutableContainers = (1UL << 0), 所有节点可变
// NSJSONReadingMutableLeaves = (1UL << 1),叶子节点可变
// NSJSONReadingAllowFragments = (1UL << 2) 根节点可变
//根节点NSDictionary,NSArray
//原生的
// NSDictionary * JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:NULL];
//JSONKit
NSDictionary * JSON = [data objectFromJSONData];
NSArray * citys = JSON[@"city"];
NSMutableArray * cityList = [NSMutableArray array];
//遍历所有城市节点
for (NSDictionary * dict in citys) {
SXTCity * city = [[SXTCity alloc] init];
[city setValuesForKeysWithDictionary:dict];
[cityList addObject:city];
}
self.dataList = cityList;
[self.tableView reloadData];
}
}];
}