1

我有以下使用 AFNetworking 获取山脉列表的 iOS 代码。我的失败块中出现“错误的 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 中无效。

我究竟做错了什么?

4

1 回答 1

3

首先,您在第一行有一个语法错误:

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

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

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

现在答案是:在将它们附加到主 URL 字符串之前,您必须对其进行百分比编码: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];

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

于 2013-05-26T19:05:55.477 回答