Objective c 目标C-HTTPGET请求API

Objective c 目标C-HTTPGET请求API,objective-c,nsurlsession,Objective C,Nsurlsession,我一直在试图查询乐购的API服务。虽然我已经在Python上轻松地处理了这个问题,但在使用Objective C发出请求时遇到了一些问题。输出中没有记录任何内容。任何帮助都将不胜感激。程序代码如下所示: #import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { NSURLSessionConfiguration *default

我一直在试图查询乐购的API服务。虽然我已经在Python上轻松地处理了这个问题,但在使用Objective C发出请求时遇到了一些问题。输出中没有记录任何内容。任何帮助都将不胜感激。程序代码如下所示:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];

        NSURL *url = [NSURL URLWithString:@"https://dev.tescolabs.com/product/?gtin=4548736003446"];
        NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

        NSString *postParams = @"subscription key=93a6e21eed2e4ca3a858a0f1fc5aaf03";
        NSData *postData = [postParams dataUsingEncoding:NSUTF8StringEncoding];

        [urlRequest setHTTPMethod:@"GET"];
        [urlRequest setHTTPBody:postData];

        NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSLog(@"Response: %@",response);
            NSLog(@"Data: %@",data);
            NSLog(@"Error: %@",error);
        }];
        [dataTask resume];
    }
    return 0;
}
#导入
int main(int argc,const char*argv[]
{
@自动释放池{
NSURLSessionConfiguration*defaultSessionConfiguration=[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession*defaultSession=[NSURLSession sessionWithConfiguration:defaultSessionConfiguration];
NSURL*url=[NSURL URLWithString:@”https://dev.tescolabs.com/product/?gtin=4548736003446"];
NSMutableURLRequest*urlRequest=[NSMutableUrlRequestWithURL:url];
NSString*postParams=@“订阅密钥=93a6e21eed2e4ca3a858a0f1fc5aaf03”;
NSData*postData=[postParams dataUsingEncoding:NSUTF8StringEncoding];
[urlRequest setHTTPMethod:@“获取”];
[UrlRequestSetHttpBody:postData];
NSURLSessionDataTask*dataTask=[defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData*数据,NSURLRResponse*响应,NSError*错误){
NSLog(@“响应:%@”,响应);
NSLog(@“数据:%@”,数据);
NSLog(@“错误:%@”,错误);
}];
[数据任务恢复];
}
返回0;
}

-dataTaskWithRequest:completionHandler:
是异步的。您正在排队等待稍后完成的操作,然后在该操作完成之前退出该程序

在退出程序之前,您需要一种等待数据任务完成的机制


请参阅:有关等待机制的示例。

尝试此操作。您需要在此请求的标头中传递订阅密钥

NSDictionary *headers = @{ @"ocp-apim-subscription-key": @"YourKey"};

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"YourURL"]
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:10.0];
[request setHTTPMethod:@"GET"];
[request setAllHTTPHeaderFields:headers];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                if (error) {
                                                    NSLog(@"%@", error);
                                                } else {
                                                    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                    NSLog(@"%@", httpResponse);
                                                }
                                            }];
[dataTask resume];

我别无选择,只能给出一个答案。。。请注意runloop代码:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];

        NSURL *url = [NSURL URLWithString:@"https://dev.tescolabs.com/product/?gtin=4548736003446"];
        NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

        NSString *postParams = @"subscription key=93a6e21eed2e4ca3a858a0f1fc5aaf03";
        NSData *postData = [postParams dataUsingEncoding:NSUTF8StringEncoding];

        [urlRequest setHTTPMethod:@"GET"];
        [urlRequest setHTTPBody:postData];

        __block BOOL done = NO;
        NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSLog(@"Response: %@",response);
            NSLog(@"Data: %@",data);
            NSLog(@"Error: %@",error);
            done = YES;
        }];
        [dataTask resume];

        while (!done) {
            NSDate *date = [[NSDate alloc] initWithTimeIntervalSinceNow:0.1];
            [[NSRunLoop currentRunLoop] runUntilDate:date];
        }
    }
    return 0;
}
#导入
int main(int argc,const char*argv[]{
@自动释放池{
NSURLSessionConfiguration*defaultSessionConfiguration=[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession*defaultSession=[NSURLSession sessionWithConfiguration:defaultSessionConfiguration];
NSURL*url=[NSURL URLWithString:@”https://dev.tescolabs.com/product/?gtin=4548736003446"];
NSMutableURLRequest*urlRequest=[NSMutableUrlRequestWithURL:url];
NSString*postParams=@“订阅密钥=93a6e21eed2e4ca3a858a0f1fc5aaf03”;
NSData*postData=[postParams dataUsingEncoding:NSUTF8StringEncoding];
[urlRequest setHTTPMethod:@“获取”];
[UrlRequestSetHttpBody:postData];
__块布尔完成=否;
NSURLSessionDataTask*dataTask=[defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData*数据,NSURLRResponse*响应,NSError*错误){
NSLog(@“响应:%@”,响应);
NSLog(@“数据:%@”,数据);
NSLog(@“错误:%@”,错误);
完成=是;
}];
[数据任务恢复];
而(!完成){
NSDate*date=[[NSDate alloc]initWithTimeIntervalSinceNow:0.1];
[[nsrunlop currentRunLoop]rununtelDate:date];
}
}
返回0;
}

基本上,您需要一个运行循环来执行后台任务

您的请求不起作用,因为未使用
GET
请求考虑正文
POST
数据。
必须在URL中传递所有参数

要实现运行循环,只需使用
CFRunLoopRun()
CFRunLoopStop()

不要使用
NSRunLoop。。。使用while循环运行untildate

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];

        NSURL *url = [NSURL URLWithString:@"https://dev.tescolabs.com/product/? ... "];

        NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithURL: url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSLog(@"Response: %@",response);
            NSLog(@"Data: %@",data);
            NSLog(@"Error: %@",error);
            CFRunLoopStop(CFRunLoopGetCurrent());
            exit(EXIT_SUCCESS);
        }];
        [dataTask resume];
    }

    CFRunLoopRun();
    return 0;
}
#导入
int main(int argc,const char*argv[]
{
@自动释放池{
NSURLSessionConfiguration*defaultSessionConfiguration=[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession*defaultSession=[NSURLSession sessionWithConfiguration:defaultSessionConfiguration];
NSURL*url=[NSURL URLWithString:@”https://dev.tescolabs.com/product/? ... "];
NSURLSessionDataTask*dataTask=[DefaultSessionDataTaskWithURL:url completionHandler:^(NSData*数据,NSURLRResponse*响应,NSError*错误){
NSLog(@“响应:%@”,响应);
NSLog(@“数据:%@”,数据);
NSLog(@“错误:%@”,错误);
CFRunLoopStop(CFRunLoopGetCurrent());
退出(退出成功);
}];
[数据任务恢复];
}
CFRunLoopRun();
返回0;
}
#导入
int main(int argc,const char*argv[]
{
@自动释放池{
NSURLSessionConfiguration*defaultSessionConfiguration=[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession*defaultSession=[NSURLSession sessionWithConfiguration:defaultSessionConfiguration];
NSURL*url=[NSURL URLWithString:@”https://dev.tescolabs.com/product/? ... "];
NSURLSessionDataTask*dataTask=[DefaultSessionDataTaskWithURL:url completionHandler:^(NSData*数据,NSURLRResponse*响应,NSError*错误){
NSLog(@“响应:%@”,响应);
NSLog(@“数据:%@”,数据);
NSLog(@“错误:%@”,错误);
CFRunLoopStop(CFRunLoopGetCurrent());
退出(退出成功);
}];
[数据任务恢复];
}
CFRunLoopRun();
返回0;
}

是否检查了完成处理程序中的错误?是的,我刚刚检查了完成处理程序中的错误,没有任何记录。还更新了URL,下面是API的来源:@Benge try error.LocalizedDescription当您说没有记录任何内容时,您的意思是错误为零,还是说从未执行
NSLog
s?没有执行NSLog@p尝试过了,没有记录错误。我不太确定是否使用信号量,因为回调可能是在主线程上传递的。喜欢使用
[nsrunlop runUntilDate::
是的,信号量方法实际上会阻止主线程。@Mazyod
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];

        NSURL *url = [NSURL URLWithString:@"https://dev.tescolabs.com/product/? ... "];

        NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithURL: url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSLog(@"Response: %@",response);
            NSLog(@"Data: %@",data);
            NSLog(@"Error: %@",error);
            CFRunLoopStop(CFRunLoopGetCurrent());
            exit(EXIT_SUCCESS);
        }];
        [dataTask resume];
    }

    CFRunLoopRun();
    return 0;
}