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.
我想对URL发出PUT请求,但是当输出显示状态代码为405时,这意味着对URL的请求不是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.
有人可以指出我出错的地方,自从过去几个小时以来我一直在阅读很多关于这个问题,但我无法弄明白。请不要将此标记为重复,因为前一个操作系统没有添加主体,这与我的代码不同。此外,提到的URL接受任何数据作为正文,所以我想我设置数据是无关紧要的。
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:
从昨天开始敲我的头后,我的一位大四学生帮助我解决了这个问题,希望这会对某人有所帮助。数据任务需要提供请求对象而不是URL,这就是它始终在Charles Web调试工具中显示“GET”的原因。代码应如下:
NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// code
}];
1 个解决方案
#1
1
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"PUT";
#1
1
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"PUT";