使用NSURLSession的HTTP PUT方法 [英] HTTP PUT method with NSURLSession

查看:115
本文介绍了使用NSURLSession的HTTP PUT方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为iOS 7 SDK中引入的NSURLSession类苦苦挣扎,我陷入了一个困境,我需要使用PUT方法调用 REST API .

I'm struggling with NSURLSession class introduced in iOS 7 SDK and I'm stuck at a point, where I need to call my REST API with PUT method.

我已经实现了GETPOST方法,使用它们可以正常工作:

I've already implemented GET and POST methods, which are working fine using this:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:httpMethod]; // GET/POST works, PUT does not
    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error){
            // do something here
            ( ... )
        } else {
            // process error
            ( ... )
        }
    }];
    [postDataTask resume];

不幸的是,将httpMethod设置为PUT似乎无效(它表现为GET).从cURL控制台调用* url的内容可以正常工作-因此API的路径是确定的.

Unfortunately, setting httpMethod to PUT doesn't seem to work (it behaves as GET). Calling contents of *url from cURL console works fine - so the path to API is OK.

如何使用NSURLSession为我的API创建有效的PUT请求?

How can I create valid PUT request to my API using NSURLSession?

推荐答案

您需要使用NSMutableURLRequest setHTTPBody方法(与POST一样)来设置数据.

You need to set the data with NSMutableURLRequest setHTTPBody method, the same as with POST.

- (void)setHTTPBody:(NSData *)data

这篇关于使用NSURLSession的HTTP PUT方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆