objective-c - Objective-C "Bad URL"错误

标签 objective-c ios nsurlconnection

我正在尝试从我的 Objective C 代码中设置对某个 URL 的 Http GET 请求。无论我做什么,或者使用哪个 URL,我都会收到以下错误:

Connection Failed: Error Domain=NSURLErrorDomain 
Code=-1000 "bad URL" UserInfo=0x755c440 
{NSUnderlyingError=0x7561950 "bad URL", NSLocalizedDescription=bad URL}

我是 iOS 开发新手,所以我不确定我这样做是否正确。我遵循了苹果文档并在各种论坛中寻找答案,即使这样我也收到了这个错误。

这是我的代码:

NSString *url = [NSString stringWithFormat: @"http://example.com/api/%@/%@", str1, str2];

NSString *encodedUrl = [url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

NSLog(@"URL - %@", encodedUrl);              // Checking the url

NSMutableURLRequest *theRequest= [[NSMutableURLRequest alloc] init];

[theRequest setHTTPMethod:@"GET"];


[NSMutableURLRequest requestWithURL:[NSURL URLWithString:encodedUrl]
                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                      timeoutInterval:10.0];

NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];

非常欢迎任何建议。

最佳答案

您没有初始化您的theRequest。 如果您不将其返回值分配给变量,则该行不会执行任何操作。

[NSMutableURLRequest requestWithURL:[NSURL URLWithString:encodedUrl]
                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                      timeoutInterval:10.0];

这是您应该使用的代码:

NSString *url = [NSString stringWithFormat: @"http://example.com/api/%@/%@", str1, str2];

NSString *encodedUrl = [url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

NSLog(@"URL - %@", encodedUrl);              // Checking the url

NSMutableURLRequest *theRequest= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:encodedUrl]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:10.0];

NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];

关于objective-c - Objective-C "Bad URL"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13914530/

相关文章:

iphone - UITableViewCell 线程中的图像缓存

objective-c - 使用 NSURLRequest 请求

ios - 我怎样才能从不同的 URL 进行多次下载?

iOS分发认证转换为p12格式

ios - UIButton 的事件 touchUpInside 不起作用

ios - 在 Swift 中将 NSMutableData 转换为 NSString

iphone - iOS 7 UIRefreshControl tintColor 不适用于 beginRefreshing

objective-c - iOS Objective-C : Unbalanced calls to begin/end appearance transitions for <GKModalRootViewController>

ios - UICollectionView header view like table view header

ios - 使用淡入淡出效果动画 CALayer mask 变化