2

我一直在开发一个 Mac 应用程序,我正在尝试从 github API 发出一个 Get HTTP 请求,但这个请求是一个条件请求,它看起来像这样:

https://api.github.com/repos/soviettoly/sandbox/events -H "If-Modified-Since: Sat, 13 Oct 2012 23:35:10 GMT"

当我根据该请求执行 curl -i 时,我得到了我想要的一切。但是,我一直在 XCode 中尝试这样做,我从 github 得到了 404。

这就是我提出请求的方式:

NSMutableString * theURL = [[NSMutableString alloc]initWithString:@"https://api.github.com/repos/soviettoly/sandbox/events -H \"If-Modified-Since: Sat, 13 Oct 2012 23:35:10 GMT\""];

NSLog(@"the normal %@",theURL);
NSString * escaped = [theURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"the escpaed %@", escaped);
NSURL * test = [NSURL URLWithString: escaped];
NSLog(@"actual URL %@",test);
NSURLRequest * request = [NSURLRequest requestWithURL:test];
[[NSURLConnection alloc]initWithRequest:request delegate:self];

NSLog 命令的打印结果给了我这个:

the normal https://api.github.com/repos/soviettoly/sandbox/events -H "If-Modified-Since: Sat, 13 Oct 2012 23:35:10 GMT"
the escpaed https://api.github.com/repos/soviettoly/sandbox/events%20-H%20%22If-Modified-Since:%20Sat,%2013%20Oct%202012%2023:35:10%20GMT%22
actual URL https://api.github.com/repos/soviettoly/sandbox/events%20-H%20%22If-Modified-Since:%20Sat,%2013%20Oct%202012%2023:35:10%20GMT%22

我不知道为什么 curl 命令给了我正确的结果,而在 XCode 中发出请求却没有。我尝试过不使用转义字符,但 XCode 不喜欢 URL,因为它包含非法字符。我不确定如何在 XCode 中进行这种调用。我一直在为 GitHub 进行其他 API 调用没问题,我只是遇到了这个问题。如果有人能支持那就太好了。非常感谢!

4

1 回答 1

2

据推测,curl您使用的命令是

curl https://api.github.com/repos/soviettoly/sandbox/events -H "If-Modified-Since: Sat, 13 Oct 2012 23:35:10 GMT"

那不是请求页面'https://api.github.com/repos/soviettoly/sandbox/events -H“If-Modified-Since: Sat, 13 Oct 2012 23:35:10 GMT”',它是在请求页面' https://api.github.com/repos/soviettoly/sandbox/events ',并发送一个额外的 HTTP 标头 ( -H),其中包含“If-Modified-Since: Sat, 13 Oct 2012 23:35:10 GMT ”。

您的 Objective-c 代码正在请求页面“https://api.github.com/repos/soviettoly/sandbox/events -H“If-Modified-Since: Sat, 13 Oct 2012 23:35:10 GMT”'。您需要使用 anNSMutableURLRequest并将其设置为将If-Modified-Since: Sat, 13 Oct 2012 23:35:10 GMT请求头包含在https://api.github.com/repos/soviettoly/sandbox/events.

例如

NSURL *url = [NSURL URLWithString:@"http://api.github.com/repos/soviettoly/sandbox/events"];
NSMutableURLRequest *request = [NSMutableURLRequest requestForURL:url];
[request setValue:@"Sat, 13 Oct 2012 23:35:10 GMT" forHTTPHeaderField:@"If-Modified-Since"];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
于 2012-10-14T02:39:11.813 回答