【发布时间】:2011-10-18 17:03:43
【问题描述】:
我正在通过 POST HTTP 方法调用 URL。当我没有连接到 3G 或 WiFi 时,它永远不会正确获取 URL,也永远不会正确获取来自 URL 的响应。 通过帖子建立联系:
NSString *URL = [NSString stringWithFormat:@"http://www.abc.com/webservices/client_server.cfc];
[[NSURLCache sharedURLCache] removeAllCachedResponses];
NSString *time_stamp =[NSString stringWithFormat:@"time_stamp=%@", self.today];
NSData *postData = [time_stamp dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *URLRequest = [[[NSMutableURLRequest alloc] init] autorelease];
[URLRequest setURL:[NSURL URLWithString:URL]];
[exhURLRequest setHTTPMethod:@"POST"];
[URLRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
[URLRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[URLRequest setHTTPBody:postData];
self.connection =[[[NSURLConnection alloc] initWithRequest:URLRequest delegate:self] autorelease];
NSAssert(self.connection != nil, @"Failure to create URL connection.");
我正在检查我是否通过以下方式获得回复:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// check for HTTP status code for proxy authentication failures
// anything in the 200 to 299 range is considered successful
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (([httpResponse statusCode]/100) == 2) {
self.data = [NSMutableData data];
} else {
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:
NSLocalizedString(@"HTTP Error",
@"Error message displayed when receving a connection error.")
forKey:NSLocalizedDescriptionKey];
NSError *error = [NSError errorWithDomain:@"HTTP" code:[httpResponse statusCode] userInfo:userInfo];
[self handleError:error];
}
}
但是当 URL 未连接时,可以说当我在地铁或其他地方时,我无法连接到 URL,它会抛出“不支持 URL”。我怎样才能避免这种情况并允许应用程序向前推进而不抛出这样的错误?如果有人使用离线重定向到应用程序而没有继续在前屏幕上等待用户。
【问题讨论】:
-
我不确定我是否在关注。你说“当我没有连接到 3G 或 Wifi 时,它永远不会正确获取 URL”。你的意思是当没有网络连接时?此外,您可能希望在创建请求的位置发布代码。
-
@onnoweb 我已经编辑了我的问题。
标签: iphone objective-c nsurlconnection nsurl