AFNetworking SPARQL查询失败,错误的URL

时间:2013-05-26 18:56:58

标签: iphone ios objective-c afnetworking sparql

我有以下iOS代码,它使用AFNetworking获取山脉列表。我的失败块中出现“错误的URL”错误。

 - (void) loadMountains
{
    NSString * loadMountainQueries = @"select * where { ?Mountain a dbpedia-owl:Mountain; dbpedia-owl:abstract ?abstract. FILTER(langMatches(lang(?abstract),"EN")) } ";        
    NSString * urlString = [NSString stringWithFormat:@"http://dbpedia.org/sparql/?query=%@",loadMountainQueries];

    NSLog(@"%@", urlString);

    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];    

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    [AFHTTPRequestOperation addAcceptableContentTypes:
     [NSSet setWithObjects:@"application/json", @"sparql-results+json", @"text/json", @"text/html", @"text/xml", nil]];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        NSLog(@"Response %@", [operation responseString]);
    }
    failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {
        NSLog(@"Response %@", [operation responseString]);
        NSLog(@"Error: %@", error);
    }];

    [operation start];
}

我假设AFHTTPRequestOperation自动编码一个URL,但只是为了确定 - 当我使用编码的URL时,它会给出相同的响应“错误的URL”。在Safari中工作的相同查询无法在目标C中工作。

我做错了什么?

1 个答案:

答案 0 :(得分:3)

首先,第一行中有语法错误:

NSString * loadMountainQueries = @"select * where { ?Mountain a dbpedia-owl:Mountain; dbpedia-owl:abstract ?abstract. FILTER(langMatches(lang(?abstract),"EN")) } ";
---------------------------------------------------------------------------------------------------------------------------------------------------------^

您应该使用反斜杠转义引号:

... ang(?abstract),\"EN\")) } ";

现在答案是:在将loadMountainQueries附加到主网址字符串之前,您必须百分比编码

NSString *loadMountainQueries = @"select * where { ?Mountain a dbpedia-owl:Mountain; dbpedia-owl:abstract ?abstract. FILTER(langMatches(lang(?abstract),\"EN\")) } ";
NSString *encodedLoadMountainQueries = [loadMountainQueries stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *urlString = [NSString stringWithFormat:@"http://dbpedia.org/sparql/?query=%@",encodedLoadMountainQueries];

该网址在Safari中有效,因为它会自动对您的网址进行百分比编码。