【问题标题】:How to use HTTP POST on Xcode [closed]如何在 Xcode 上使用 HTTP POST [关闭]
【发布时间】:2013-07-31 16:11:06
【问题描述】:

抱歉,这里是初学者问题。我正在尝试使用 HTTP post 从 URL 检索 XML 文档,并且我需要在 POST 请求中包含一些参数。我从this website 中获得了代码Objective C 部分,我开始理解它。但我现在需要尝试做的是在我的应用程序中使用该类。以下是我需要包含的参数:

URL: https://admin.poslavu.com/cp/reqserv/ 
dataname=tangere_techno&key=dBkeY&token=dBt0kEn&table=menu_groups



【问题讨论】:

    标签: ios http http-post


    【解决方案1】:

    试试:

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://admin.poslavu.com/cp/reqserv/"]];
    [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
    [request setHTTPBody:[[NSString stringWithFormat:@"dataname=tangere_techno&key=dBkeY&token=dBt0kEn&table=menu_groups"] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPMethod:@"POST"];
    NSError *error = nil; NSURLResponse *response = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    if (error) {
        NSLog(@"Error:%@", error.localizedDescription);
    }
    else {
        //success
    }
    

    数据应该是您的 XML 信息,不过您需要先对其进行解析。您应该尝试查看 Apple 的文档以获取更多信息。如果您尝试异步发出请求,请尝试以下操作:

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://admin.poslavu.com/cp/reqserv/"]];
    [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
    [request setHTTPBody:[[NSString stringWithFormat:@"dataname=tangere_techno&key=dBkeY&token=dBt0kEn&table=menu_groups"] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPMethod:@"POST"];
    
    
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:req];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){
        NSData *data = (NSData *)responseObject;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    [operation start];
    

    【讨论】:

    • 谢谢,在接受之前,我想问一下如何记录回复?
    • 此代码存在三个问题:1) 您没有正确检查错误情况。您可能想知道为什么有时会记录错误而实际上没有错误。 2)您使用同步方法调用来进行固有的异步操作。这将不必要地产生一个线程并在网络请求期间阻塞它。这至少不是最理想的——但当 RAM 稀缺时可能会成为一个大问题(在移动设备上总是如此)。 3)您没有检查响应的 HTTP 状态代码和 MIME 类型。这是您应该做的最少检查。
    • @MichaelScaria 我正要放弃,非常感谢!!!!!!
    • @CouchDeveloper 那你有替代代码吗??
    • 是的,我有 ;) 但在我回答之前,您也可以使用以下关键词进行搜索:“NSURLConnection”、“异步”、“POST”。我相信你会找到答案的。此外,请参阅 Apple 文档以了解 NSURLConnection,还有简单 POST 请求的示例,阅读如何检查最后一个参数是指向 NSError* 的指针的方法的错误。
    猜你喜欢
    • 1970-01-01
    • 2019-11-19
    • 2013-07-23
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 2013-03-22
    • 1970-01-01
    相关资源
    最近更新 更多