准备GET / POST请求以在iPhone上获取数据

时间:2013-05-18 22:15:09

标签: iphone ios nsurlconnection asihttprequest

我正在尝试以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];         [请求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 个答案:

答案 0 :(得分:0)

     -(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];

        }

答案 1 :(得分:0)

在代码中设置multipart / form-data请求。虽然这个成就是可信的,但并不是你如何与给定的Web服务的API进行对话。

事实上,它更简单:

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

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

“非分层数据”的含义并未明确指定,但在几乎所有情况下,Web服务都需要将查询字符串作为键/值对列表,其键和值之间用'='分隔,并且对由“&”分隔:

param1=value1&param2=value2

此外,为了消除查询字符串的歧义,例如当值或键本身包含“特殊字符”时,如空格,非ASCII字符,符号或等号等,查询字符串必须正确“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标头和查询字符串。