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

时间:2014-04-03 10:55:13

标签: ios http nsurlconnection nsurlrequest

我正在寻找一个在iOS中发送和接收http GET请求的示例。我只想要 do是处理后台线程中的通信,这样它就不会阻塞主线程 并且还想处理http标准错误代码。任何人都可以建议我参考代码或 处理http响应数据和处理正确的内存管理的示例?

任何帮助都会感激不尽。

1 个答案:

答案 0 :(得分:1)

实现它的两种方法:

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委托方法以获得响应:

// 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
}