iOS使用NSURLConnection發送同步和非同步HTTP Request

來源:互聯網
上載者:User

標籤:http   io   ar   os   使用   sp   for   strong   on   

  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); 

iOS使用NSURLConnection發送同步和非同步HTTP Request

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.