1. 同步發送
- (NSString *)sendRequestSync { // 初始化請求, 這里是變長的, 方便擴展 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; // 設置 [request setURL:[NSURL URLWithString:urlStr]]; [request setHTTPMethod:@"POST"]; [request setValue:host forHTTPHeaderField:@"Host"]; NSString *contentLength = [NSString stringWithFormat:@"%d", [content length]]; [request setValue:contentLength forHTTPHeaderField:@"Content-Length"]; [request setHTTPBody:content]; // 發送同步請求, data就是返回的數據 NSError *error = nil; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error]; if (data == nil) { NSLog(@"send request failed: %@", error); return nil; } NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"response: %@", response); return response; }
2.異步發送
1) 使用delegate的方式:
- (void)sendRequestAsync { // 初始化請求 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; // 設置 [request setURL:[NSURL URLWithString:urlStr]]; [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; // 設置緩存策略 [request setTimeoutInterval:5.0]; // 設置超時 //...... receivedData = [[NSMutableData alloc] initData: nil]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; if (connection == nil) { // 創建失敗 return; } }
異步發送使用代理的方式, 需要實現以下delegate接口:
// 收到回應 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@"receive the response"); // 注意這里將NSURLResponse對象轉換成NSHTTPURLResponse對象才能去 NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response; if ([response respondsToSelector:@selector(allHeaderFields)]) { NSDictionary *dictionary = [httpResponse allHeaderFields]; NSLog(@"allHeaderFields: %@",dictionary); } [receivedData setLength:0]; } // 接收數據 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { NSLog(@"get some data"); [receivedData appendData:data]; } // 數據接收完畢 - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSString *results = [[NSString alloc] initWithBytes:[receivedData bytes] length:[receivedData length] encoding:NSUTF8StringEncoding]; NSLog(@"connectionDidFinishLoading: %@",results); } // 返回錯誤 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"Connection failed: %@", error); }
2) iOS 5.0版本新增異步發送接口:
+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue*) queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*)) handlerNS_AVAILABLE(10_7, 5_0);