2

我正在尝试从我的 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];

任何建议都是最受欢迎的。

4

1 回答 1

4

你没有初始化你的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];
于 2012-12-17T12:55:26.240 回答