Problems encountered in DELETE requests in AFNetworking

Keywords: network JSON

Today is the first week of BUG testing. There is a strange problem. DELETE requests to transfer data:

NSDictionary *parameters = @{@"objtype":@"course_thread"};
//Send network request (request method is DELETE)
    [manager DELETE:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
Is it OK to drive like this? But the server received the data!!!!! Tearful, I thought it was my own problem. After all kinds of debugging, I couldn't find a way to check the source code of the parameters in AFNetworking

It is found that the DELETE mode uses the same method as GET or HEAD mode, so the background cannot accept the data. How to solve this problem?



Method 1: find the source code and

 self.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", @"DELETE", nil];
DELETE in

Method 2: modify during encapsulation and remove DELETE. Of course, the second method is recommended

NSDictionary *parameters = @{@"objtype":@"course_thread"};
   manager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", nil];
    
    //Send network request (request method is DELETE)
    
    [manager DELETE:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];

Method 3: do not rely on AFNworking and write your own request

NSString * url = @"url address";
    NSMutableURLRequest * req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    req.HTTPMethod = @"DELETE";
    req.HTTPBody = [dic JSONData];//The dic dictionary is equivalent to parameters, which are in the request body
    req.allHTTPHeaderFields = @{
                                @"Content-Type":@"application/json"
                                };//Ask for something in the head
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:req queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError) {
            //fail
        } else {
            //Success
        }
    }];

All three methods are feasible. The second one is recommended......


Posted by NikLP on Sun, 03 May 2020 22:23:18 -0700