问题
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