使用NSURLSession的HTTP PUT方法
我在iOS 7 SDK中引入的NSURLSession
类中挣扎,而且我被困在一个地方,我需要用PUT
方法调用REST API 。
我已经实现了GET
和POST
方法,使用这个工作正常:
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的path是确定的。
我如何使用NSURLSession
创build有效的PUT
请求到我的API?
您需要使用NSMutableURLRequest
setHTTPBody
方法设置数据,与POST相同。
- (void)setHTTPBody:(NSData *)data