網(wǎng)絡(luò)
NSURLConnection
常用類
lNSURL:請求地址
lNSURLRequest:一個NSURLRequest對象就代表一個請求,它包含的信息有
一個NSURL對象
請求方法、請求頭、請求體
請求超時
… …
lNSMutableURLRequest:NSURLRequest的子類
lNSURLConnection
負(fù)責(zé)發(fā)送請求,建立客戶端和服務(wù)器的連接
發(fā)送數(shù)據(jù)給服務(wù)器,并收集來自服務(wù)器的響應(yīng)數(shù)據(jù)

Snip20151017_4.png
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//1.創(chuàng)建url
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
//2.創(chuàng)建請求(默認(rèn)發(fā)的是GET請求)(如果想發(fā)送的是POST請求,需要使用可變請求,并且改變可變請求中的)
//2.1 NSURLRequest:不可變的請求:無法改變請求中的 請求頭, 請求體;
// NSURLRequest *request = [NSURLRequest requestWithURL:url];
//2.2 NSMutableURLRequest:可以修改請求中的請求頭和請求體信息(一般都用這個);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//改變請求方法
request.HTTPMethod = @"POST";
//改變請求體
NSString *username = @"520it";
// 防止出現(xiàn)中文無法識別,需要進(jìn)行轉(zhuǎn)碼
username = [username stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *pwd = @"520it";
NSString *str = [NSString stringWithFormat:@"username=%@&pwd=%@",username, pwd];
request.HTTPBody = [str dataUsingEncoding:NSUTF8StringEncoding];
//3.創(chuàng)建 NSURLConnection(有三種方式)
//異步
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//回調(diào)block(拿到響應(yīng)的一些數(shù)據(jù))
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}];
//同步
// 兩個*代表傳入一個指針,系統(tǒng)拿到后可以修改對應(yīng)地址的值
NSURLResponse *res = nil;
NSError *error = [[NSError alloc]init];
[NSURLConnection sendSynchronousRequest:request returningResponse:&res error:&error];
//使用代理
NSURLConnection *conne = [[NSURLConnection alloc] initWithRequest:request delegate:self];//使用代理
[NSURLConnection connectionWithRequest:request delegate:self];
NSURLConnection *conne2 = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
}
#pragma mark - NSURLConnectionDataDelegate
//接收到服務(wù)器的響應(yīng)
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
}
//接收到服務(wù)器傳來的數(shù)據(jù)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
}
//出現(xiàn)問題
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}
//結(jié)束加載
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
}
- Posted by 簡書.lovepeijun