iOSBodyraw请求

iOS高级程序师技术群:622177838,期待你的加入

+ (void)postBodyWithURL:(NSString*)urlbody:(NSData*)bodyandParameters:(NSDictionary*)paramssuccess:(void(^)(id_Nonnull))successfailure:(void(^)(NSError*_Nonnull))failure {


    NSError*error;

    NSData*jsonData = [NSJSONSerializationdataWithJSONObject:paramsoptions:0error:&error];

    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];


    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

    //method 为时post请求还是get请求

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

    //设置超时时长

    request.timeoutInterval=30;

    [requestsetValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    //将对象设置到requestbody中 ,主要是这不操作

    [requestsetHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];

    //进行网络请求

    [[managerdataTaskWithRequest:requestuploadProgress:^(NSProgress*_NonnulluploadProgress) {


    }downloadProgress:^(NSProgress*_NonnulldownloadProgress) {


    }completionHandler:^(NSURLResponse*_Nonnullresponse,id_NullableresponseObject,NSError*_Nullableerror) {


        if(!error) {


            NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];


//            NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];


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


            success(dic);


        }else{

            failure(error);

        }

    }]resume];

}

你可能感兴趣的:(iOSBodyraw请求)