10.1 GET請求html
10.2 XML解析git
10.3 JSON解析github
10.4 POST請求web
經過一個第三方提供的雲服務,查詢IP歸屬地:http://www.youdao.com/smartresult-xml/search.s?type=ip&q=218.241.121.186json
它的返回格式是xml :api
新建個例子:CSSimpleXML,設計原型:xcode
編輯按鈕事件:服務器
- (IBAction)query:(id)sender { NSString* strUrl = [NSString stringWithFormat:@"http://www.youdao.com/smartresult-xml/search.s?type=ip&q=%@", ipText.text]; NSURL* url = [NSURL URLWithString:strUrl]; NSURLRequest* request = [[NSURLRequest alloc]initWithURL:url]; NSURLConnection* connection = [[NSURLConnection alloc]initWithRequest:request delegate:self]; [connection release]; [request release]; [activityIndicator startAnimating]; }
定義NSURLConnection的委託:app
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];工具
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
委託(delegate)是一種事件處理機制,當知足條件時候觸發。delegate:self說明是委託當前對象處理事件,咱們須要實現它們回調方法。
NSURLConnection 回調方法
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 請求成功,而且接收數據。 -(void) connection:(NSURLConnection *)connection didFailWithError: (NSError *)error 請求成功,可是加載數據出現異常。 -(void) connectionDidFinishLoading: (NSURLConnection*) connection加載數據成功,在connection:didReceiveData方法以後執行。
接收數據處理
-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData *)data { //默認對於中文的支持很差 NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000); NSString* gbkNSString = [[NSString alloc]initWithData:data encoding:enc]; //若是是黑UTF-8 NSXMLParese會報錯 xmlString = [[NSString alloc]initWithString:[gbkNSString stringByReplacingOccurrencesOfString:@"<?xml version=\"1.0\" encoding=\"gbk\"?>" withString:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>"]]; NSLog(@"%@", xmlString); [gbkNSString release]; }
iPhone SDK提供的XML解析類只能解析utf-8編碼,若是從服務器返回的xml編碼是gbk等,要轉換成utf-8再開始解析。
關於iPhone發送GET請求,就是經過NSURLRequest和NSURLConnection兩個類實現的。
在衆多的回調方法。解析XML是在 connectionDidFinishLoading:方法開始的。
解析XML文件也是要經過XML回調方式實現解析處理的。
NSXMLParser,是iPhone解析XML SDK工具類。
NSXMLParser採用SAX方式而不是DOM方式解析,SAX是基於事件觸發的解析方式,解析器從上到下遍歷xml文檔,遇到開始標籤、結束標籤、文檔開始、文檔結束和字符串都會觸發事件。
解析開始處理
-(void)connectionDidFinishLoading:(NSURLConnection*)connection { [activityIndicator stopAnimating]; //開始解析XML NSXMLParser* ipParser = [[NSXMLParser alloc]initWithData:[xmlString dataUsingEncoding:NSUTF8StringEncoding ]];; ipParser.delegate = self; [ipParser parse]; [ipParser release]; }
NSXMLParser回調方法
- (void)parserDidStartDocument:(NSXMLParser *)parser文檔開始的時候觸發 - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError 文檔出錯的時候觸發 - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *) qualifiedName attributes:(NSDictionary *)attributeDict 遇到一個開始標籤時候觸發。 - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string 遇到字符串時候觸發 - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementNamenamespaceURI:(NSString *) namespaceURIqualifiedName:(NSString *)qName 遇到結束標籤時候出發。 - (void)parserDidEndDocument:(NSXMLParser *)parser 遇到文檔結束時候觸發。
文檔開始的回調方法
這個方法在解析過程當中只調運一次,通常在這個方法中進行有關解析的初始化處理。
//文檔開始的時候觸發 - (void)parserDidStartDocument:(NSXMLParser *)parser { info = [[NSMutableDictionary alloc]initWithCapacity:1]; }
文檔出錯回調方法
//文檔出錯的時候觸發 - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError { UIAlertView* errorAlert = [[UIAlertView alloc]initWithTitle:[parseError localizedDescription] message:[parseError localizedFailureReason] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [errorAlert show]; [errorAlert release]; }
遇到開始標籤回調方法
參數elementName是標籤的名字,attributeDict 是屬性列表,namespaceURI 是命名空間,若是有命名空間qualifiedName是指定的前綴名。
//遇到一個開始標籤時候觸發。 - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *) qualifiedName attributes:(NSDictionary *)attributeDict { NSLog(@"value:%@\n", elementName); currentTagName = elementName; }
遇到字符串回調方法
//遇到字符串時候觸發 - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { NSLog(@"value:%@\n", string); string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""]; if ([currentTagName isEqualToString:@"ip"]) { if (![string isEqualToString:@""]) { [info setValue:string forKey:currentTagName]; } } else if([currentTagName isEqualToString:@"location"]) { if (![string isEqualToString:@""]) { [info setValue:string forKey:currentTagName]; } } }
遇到結束標籤回調方法
//遇到結束標籤時候出發。 - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementNamenamespaceURI:(NSString *)namespaceURIqualifiedName:(NSString *)qName { }
遇到結束文檔回調方法
// 遇到文檔結束時候觸發。 - (void)parserDidEndDocument:(NSXMLParser *)parser { NSMutableString* outString = [[NSMutableString alloc]initWithCapacity:1]; for (id key in info) { [outString appendFormat:@"%@:%@\n", key, [info objectForKey:key]]; } msgText.text = outString; [outString release]; [xmlString release]; }
http://www.geonames.org/export/ws-overview.html
得到JSON:
{ status = { message = "the daily limit of 30000 credits demo has been exceeded.Please throttle your requests or use the commercial service."; value = 18; }; }
iPhone SDK沒有提供JSON解析API,可使用第三方的API類庫json-framework,下載地址:
https://github.com/stig/json-framework/
把Classes/JSON/下面的類拷貝到咱們的工程的Classes目錄下面,右鍵添加存在的類文件。
實現回調方法
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data - (void) connectionDidFinishLoading: (NSURLConnection*) connection -(void) connection:(NSURLConnection *)connection didFailWithError: (NSError *)error
connection:didReceiveData:
-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData *)data { outString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", outString); }
connectionDidFinishLoading:
outString的 JSONValue消息得到NSMutableDictionary,JSON api中提供了NSString的分類(Catelog)
-(void)connectionDidFinishLoading:(NSURLConnection*)connection { NSMutableDictionary* jsonObj = [outString JSONValue]; NSLog(@"%@", jsonObj); NSMutableDictionary* jsonSubObj = [jsonObj objectForKey:@"status"]; NSString* text = [[NSString alloc]initWithFormat:@"message=%@\n\nvalue=%@", [jsonSubObj objectForKey:@"message"],[jsonSubObj objectForKey:@"value"]]; mstText.text = text; [text release]; [outString release]; [activity stopAnimating]; }
文檔出錯回調方法
-(void) connection:(NSURLConnection *)connection didFailWithError: (NSError *)error { UIAlertView* errorAlert = [[UIAlertView alloc]initWithTitle:[error localizedDescription] message:[error localizedFailureReason]
delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [errorAlert show]; [errorAlert release]; }
點擊按鈕事件
-(IBAction)go:(id)sender{ NSString *strurl =@"http://api.geonames.org/findNearByWeatherJSON?lat=43&lng=-2&username=demo"; NSURL *url = [NSURL URLWithString:strurl]; NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url]; NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self]; [connection release]; [request release]; [activityIndicatorView startAnimating]; }
爲了學習iPhone的POST請求,安排案例以下:
在畫面中輸入用戶名和密碼,而後以POST方式提交數據到服務器端。
POST請求與GET不一樣,不使用的NSURLRequest,而是使用NSMutableURLRequest類,這是一個可變的NSURLRequest類。
- (IBAction)login:(id)sender { //http://www.sunnyer.com/shop/member!login.action //member.email:dfgdrgdg@af.cd //member.password:dfgdfgrf [activity startAnimating]; NSString* post = [NSString stringWithFormat:@"memberIdOrCellphoneOrEmail=%@&&password=%@", username.text, password.text]; NSData* postData = [post dataUsingEncoding:NSUTF8StringEncoding]; NSURL* postServierURL = [NSURL URLWithString:@"http://www.jinjiang.com/membercenter/member/ordinaryLogin"]; NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:postServierURL]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:postData]; NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; if (!connection) { NSLog(@"Failed to submit request"); } else { NSLog(@"Request submitted"); } [connection release]; }
POST參數是以一個字符串方式傳遞: memberIdOrCellphoneOrEmail=%@&&password=%@
[request setHTTPMethod:@"POST"];
知道請求方法爲POST方法,可是要注意POST必須大寫。
[request setHTTPBody:postData];該語句是將要提交的數據放到請求體中。
connection:didReceiveData:
-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData *)data { outString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", outString); }
connectionDidFinishLoading:
-(void)connectionDidFinishLoading:(NSURLConnection*)connection{ NSLog(@"%@", outString); [webView loadHTMLString:outString baseURL:[[NSURL alloc]initWithString:@"http://www.jinjiang.com"]]; [activity stopAnimating]; }
文檔出錯回調方法
-(void) connection:(NSURLConnection *)connection didFailWithError: (NSError *)error { UIAlertView* errorAlert = [[UIAlertView alloc]initWithTitle:[error localizedDescription] message:[error localizedFailureReason]
delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[errorAlert show];
[errorAlert release];
}
注:
1 本教程是基於關東昇老師的教程
2 基於黑蘋果10.6.8和xcode4.2
3 本人初學,有什麼不對的望指教
4 教程會隨着本人學習,持續更新
5 教程是本人從word筆記中拷貝出來了,因此格式請見諒
做者: syxChina
出處: http://syxchina.cnblogs.com、 http://hi.baidu.com/syxcs123
本文版權歸做者、博客園和百度空間共有,歡迎轉載,但未經做者贊成必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接,不然做者會詛咒你的。
若是您閱讀了個人文章並以爲有價值請點擊此處,謝謝您的確定1。