詳談iPhone中網路請求是本文要介紹的內容,主要介紹了網路編程的相關內容,很詳細的介紹了如何獲得或者發送網路請求。不多說,我們先來看詳細內容。
一、簡單的get請求
網路編程是我們經常遇到的,在IPhone中,SDK提供了良好的介面,主要使用的類有NSURL,NSMutableURLRequest,NSURLConnection等等。一般情況下建議使用非同步接收資料的方式來請求網路連接,這種網路連接分為兩步,第一步是建立NSURLConnection對象後,直接調用它的start方法來串連網路。第二步是使用delegate方式來接收資料,這裡給一個常用的寫法:
網路請求部分:
- NSString *urlString = [NSString stringWithFormat:@"http://www.voland.com.cn:8080/weather/weatherServlet?city=%@",kcityID];
- NSURL *url = [NSURL URLWithString:urlString];
- NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
- NSURLConnection *aUrlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:true];
- self.urlConnection = aUrlConnection;//這裡的urlConnection在標頭檔中定義的變數
- [self.urlConnection start];//開始串連網路
- [aUrlConnection release];
- [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
接收資料部分,接收到的資料主要是在這裡處理
- - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
- NSLog(@"接收完響應:%@",response);
- }
- - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
- NSLog(@"接收完資料:");
- }
- - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
- NSLog(@"資料接收錯誤:%@",error);
- }
- - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
- NSLog(@"串連完成:%@",connection);
- [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
- }
二、Post請求
進行post請求,主要是設定好NSMutableURLRequest對象,在get請求中,我們都使用了預設的,實際這些request內容都可以設定的。設定好後,其它與get方式同:
- NSString *content=[[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
- [request setHTTPBody: content];
- [request setHTTPMethod: @"POST"];
- [request setValue:@"Close" forHTTPHeaderField:@"Connection"];
- [request setValue:@"www.voland.com.cn" forHTTPHeaderField:@"Host"];
- [request setValue:[NSString stirngWithFormat@"%d",[content length]] forHTTPHeaderField:@"Content-Length"];
小結:詳談iPhone中網路請求的內容介紹完了,希望本文對你有所協助!