【问题标题】:Preparing a GET/POST request to fetch data on iPhone准备 GET/POST 请求以在 iPhone 上获取数据
【发布时间】:2013-05-13 19:54:08
【问题描述】:

我正在尝试以 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"]; [请求设置 URL:requestURL]; [请求 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);
                               }

                           }];

【问题讨论】:

  • 显示一些你尝试过的代码。

标签: iphone ios nsurlconnection asihttprequest


【解决方案1】:

在您的代码中,您设置了一个 multipart/form-data 请求。虽然成就是值得信赖的,但这并不是您与给定 Web 服务的 API 对话的方式。

其实更简单:

您可以从该站点的文档中检索到,“查询参数”作为查询字符串进入 URL:“q=cancer”。然后,只需将 Content-Type 标头指定为“application/json” - 它应该可以工作。

一般情况下,URL 查询参数将通过附加一个“?”来附加到 URL,然后是包含查询字符串的“非分层数据”,然后是可选的“#”。

“非分层数据”的含义并未具体说明,但在几乎所有情况下,Web 服务都需要一个查询字符串作为键/值对列表,其键和值由“=”分隔,并且对由“&”分隔:

param1=value1&param2=value2

此外,为了消除查询字符串的歧义,例如当值或键本身包含“特殊字符”时,如空格、非 ASCII 字符、& 或等号等,查询字符串必须正确“URL 编码”之前附加到 url 并发送到服务器。

可以在相应的 RFC 中找到构建 URL 的详细信息。但是,wiki 以更简洁的形式提供了查询字符串的易于理解的定义: http://en.wikipedia.org/wiki/Query_string

有关如何使用方便的方法或函数“URL 编码”查询字符串的更多信息,请阅读NSString 文档,stringByAddingPercentEscapesUsingEncoding:https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html 和核心基金会:CFURLCreateStringByAddingPercentEscapeshttps://developer.apple.com/library/mac/#documentation/CoreFOundation/Reference/CFURLRef/Reference/reference.html

第三方库可能会更方便,但您应该了解该 API 的含义以及您必须如何自己构建 URL、HTTP 标头和查询字符串。

【讨论】:

    【解决方案2】:
         -(AFHTTPClient *) getHttpClient{
                AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:[NSURL URLWithString:kBASEURL]];
                httpClient.parameterEncoding = AFJSONParameterEncoding;
                [httpClient setDefaultHeader:@"Accept" value:@"application/json"];
                [httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
    
                return httpClient;
            }
    
    
    
            //This is how you should call
    
    -(void) callAPI{
    
                AFHTTPClient *httpClient = [self getHttpClient];
                NSMutableURLRequest  *request = [httpClient requestWithMethod:@"GET" path:method parameters:queryStrDictionary];// querystringDictionary contains value of all q=? stuff 
    
                AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
                    //You have Response here do anything you want.
                    [self processResponseWith:JSON having:successBlock andFailuerBlock:failureBlock];
    
                } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
                    //Your request failed check the error for detail
                    failureBlock(error);
                }];
    
                NSOperationQueue *queue = [[NSOperationQueue alloc] init] ;
                [queue addOperation:operation];
    
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-16
      • 2014-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多