iOS puts request parameters into body for network request

The project needs to pack the relevant parameters in the body when the network request is made. Since this kind of operation is rarely encountered before, so make a record here. The specific code is as follows:

NSString *dicTojson = @"dictionary to string parameter";

NSString *url = [NSString stringWithFormat:@"%@VMS2Service.cgi?Cmd=%@",baseUrl, method];

    NSData *body = [dicTojson dataUsingEncoding:NSUTF8StringEncoding]

    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer]requestWithMethod:requestType URLString:url parameters:nil error:nil];

    [request setHTTPMethod:requestType];

    [request setValue:authToken forHTTPHeaderField:@"Auth-Token"];

    [request setHTTPBody:body];

     //Set the timeout

    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];

    sessionConfig.timeoutIntervalForRequest = 15.0;

    sessionConfig.timeoutIntervalForResource = 15.0;

    NSURLSession *session = [NSURLSession sharedSession];;

    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        if(error==nil){

            NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

                if (failure) {

                    failure(errorMsg);

                }

            }else{

                if(success){

                    success(dict);

                }

            }

        }else{

            if (failure) {

                failure(@"server timeout");

            }

        }

    } ];

    [dataTask resume];

The AFN method can be used for reference:  ios uses AFNetworking to pass the object as a parameter (put into the body) to the background - Short Book

Guess you like

Origin blog.csdn.net/ForeverMyheart/article/details/123006996