iOS 網絡的請求

既然上篇文章說到了網絡的判斷,那這篇文章就來講一下網絡的請求吧,如有不對,敬請糾正微笑
請求方式:GET、POST、SOAP

GET->構建不可變的請求對象

1.構建網絡資源路徑
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];


2.構建請求對象
NSURLRequest *request = [NSURLRequest requestWithURL:url];


3.1 構建連接對象(同步:會造成界面假死)
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];


3.2 構建連接對象(異步:多線程)推薦用法
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[conn start];


實現NSURLConnectionDataDelegate協議方法


已經接收到響應頭
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response


開始接收數據:可能調用多次
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data


連接失敗
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error


連接已完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection


POST->構建可變的請求對象
1 設置請求方式
[request setHTTPMethod:@"POST"];


2 設置請求內容
NSString *body = [NSString stringWithFormat:@"mobileCode=%@&userID=",self.txtPhone.text];
NSData *bodyData = [body dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:bodyData];


3 設置請求頭
NSString *bodyLen = [NSString stringWithFormat:@"%i",[bodyData length]];
[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request addValue:bodyLen forHTTPHeaderField:@"Content-Length"];

構建連接對象同上,就不贅述來哈!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章