Tejas K
Tejas K

Reputation: 700

How to make a PUT request in NSURLSession?

I want to make a PUT request to a URL, but when the output shows status code as 405, which means the request to the URL is something other than put.

NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];

NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

NSURL * url = [NSURL URLWithString:@"http://httpbin.org/put"];

NSMutableURLRequest *request =[[NSMutableURLRequest alloc]initWithURL:url];
NSData *postbody = [@"name=testname&suggestion=testing123" dataUsingEncoding:NSUTF8StringEncoding];


[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

request.HTTPMethod = @"PUT";
[request setHTTPBody:postbody];


NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithURL:url
                                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

                                                    if(error == nil)
                                                    {
                                                        [request setHTTPBody:data];
                                                        NSLog(@"Response = %@",response);
                                                    }

                                                }];

[dataTask resume];

Can someone point out where i am going wrong, i have been reading a lot about this issue since the last couple of hours, but i am not able to figure it out. Kindly do not mark this as duplicate since the previous op did not add body which is not the case with my code. Also the URL mentioned accepts any data as body, so i guess what i set the data to is irrelevant.

EDIT (ANSWER):

After banging my head from yesterday, one of my senior helped me solve the issue, hope this will help someone. The data task needs to be supplied with the request object and not with the URL, this was the reason it always showed 'GET' in Charles web debugging tool. The code should be as follows:

NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithRequest:request
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
       // code
}];

Upvotes: 3

Views: 4276

Answers (1)

Anand
Anand

Reputation: 71

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"PUT";

Upvotes: 1

Related Questions