HTTP PUT method with NSURLSession

余生颓废 提交于 2019-12-23 07:26:48

问题


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.

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

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.

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


回答1:


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

- (void)setHTTPBody:(NSData *)data


来源:https://stackoverflow.com/questions/19860229/http-put-method-with-nsurlsession

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!