ios - 如何从ios中的非ui线程发送http请求

标签 ios http nsurlconnection nsurlrequest

我正在寻找在 iOS 中发送和接收 http GET 请求的示例。所有我想要的 do 是在后台线程中处理通信,这样它就不会阻塞主线程 并且还想处理 http 标准错误代码。谁能建议我引用代码或 处理 http 响应数据和处理适当内存管理的示例?

如有任何帮助,我们将不胜感激。

最佳答案

两种实现方式:

1) NSURLCOnnection sendAsynchronousRequest 方法:

NSString *strURL= [NSString stringWithFormat:@"http://www.google.com/"];
NSURL *URL = [NSURL URLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *requestURL = [[NSURLRequest alloc] initWithURL:URL];
[NSURLConnection sendAsynchronousRequest:requestURL
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data,        NSError *error)
 {      
     NSLog(@"Response is:%@",[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
 }];

2) 创建并触发请求,然后 NSURLConnection 委托(delegate)方法获取响应:

// Create the request.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL     URLWithString:@"http://google.com"]];

// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse  *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
_responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[_responseData appendData:data];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
              willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection 
return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// The request has failed for some reason!
// Check the error var
}

关于ios - 如何从ios中的非ui线程发送http请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22835397/

相关文章:

node.js - 如何在一个 Node 服务器中绑定(bind) http 和 https

cocoa - 区分 delegate 中的 NSURLConnection 对象

ios - 停止当前的 NSURLConnection

c# - 异步等待调用后的 Console.WriteLine。

security - HTTP 授权 header - 不记名 token 安全

ios - 如何根据按下的 UIButton 重新填充表格 View ?

android - 独立世博会(ExpoKit)推送通知

ios - 如何将委托(delegate)与 NSURLSession 一起使用

ios - 自定义 UITableViewCell 中的 contentView 宽度错误?

iOS swift后台线程阻塞主线程