我正在尝试以JSON格式获取搜索词“癌症”的数据 .
但我无法弄清楚如何调用websvice,我尝试了一些东西,但他们没有工作,任何人都可以帮助我 .
以下是我应该调用的API https://api.justgiving.com/docs/resources/v1/Search/FundraiserSearch
单击以下URL将在浏览器中获得所需数据 . https://api.justgiving.com/2be58f97/v1/fundraising/search?q=cancer
apiKey = 2be58f97
这是我正在使用的代码:
NSMutableURLRequest * request = [[NSMutableURLRequest alloc] init]; NSURL * requestURL = [NSURL URLWithString:@“https://api.justgiving.com/2be58f97/v1/fundraising/search "]; [request setURL:requestURL]; [request setHTTPMethod:@" GET”];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"q\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@",searchText] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(@"ERROR = %@",error.localizedDescription);
if(error.localizedDescription == NULL)
{
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"response >>>>>>>>> %@",returnString);
}
else
{
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"response >>>>>>>>> %@",returnString);
}
}];
2 回答
在您的代码中,您设置了multipart / form-data请求 . 虽然成就是可信的,但这并不是您与给定Web服务的API交谈的方式 .
事实上,它更简单:
您可以从该站点的文档中检索“查询参数”作为查询字符串进入URL:“q = cancer” . 然后,只需将Content-Type标头指定为“application / json” - 它应该可以工作 .
通常,URL查询参数将通过附加“?”后跟URL,然后是包含查询字符串的“非分层数据”,然后是可选的“#” .
“非分层数据”的含义并没有明确规定,但几乎在所有情况下,Web服务都需要一个查询字符串作为键/值对的列表,其键和值之间用'='分隔,并且这些对被分开通过'&':
param1=value1¶m2=value2
此外,为了消除查询字符串的歧义,例如当值或键本身包含“特殊字符”(如空格,非ASCII字符,符号或等号等)时,查询字符串必须正确地“URL编码” “在附加到网址并发送到服务器之前 .
可以参考相应的RFC找到构建URL的细节 . 但是,wiki以更简洁的形式提供了一个可理解的查询字符串定义:http://en.wikipedia.org/wiki/Query_string
有关如何"URL encode"使用方便的方法或函数的查询字符串的更多信息,请阅读
NSString
文档,stringByAddingPercentEscapesUsingEncoding:
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html和Core Foundation:CFURLCreateStringByAddingPercentEscapes
:https://developer.apple.com/library/mac/#documentation/CoreFOundation/Reference/CFURLRef/Reference/reference.html第三方库可能会使这更方便,但您应该了解该API的含义以及您将如何自己构建URL,HTTP标头和查询字符串 .