AFNetworking Post 请求

<span style="color:#ff0000;">封装  .h文件</span>
#import <Foundation/Foundation.h>
#import <AFNetworking.h>
@interface MSHttpRequest : NSObject

+ (void)post:(NSString *)url params:(NSDictionary *)params success:(void (^)(id json))success failure:(void (^)(NSError *error))failure;

@end

.m文件

#import "MSHttpRequest.h"

@implementation MSHttpRequest


+ (void)post:(NSString *)url params:(NSDictionary *)params success:(void (^)(id json))success failure:(void (^)(NSError *error))failure
{
    static NSString *http = @"http://192.168.0.216:8080/app";
    NSString *str = [http stringByAppendingString:url];
   
    // 1.创建请求管理者
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    
    // 2.添加固定的请求头
    manger.requestSerializer = [AFJSONRequestSerializer serializer];
    manger.responseSerializer = [AFJSONResponseSerializer serializer];
    [manger.requestSerializer setValue:@"1.0.0" forHTTPHeaderField:@"app.version"];
    [manger.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"os"];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *loginUserId =  [userDefaults objectForKey:USERLOGINID];
    // NSLog(@"*************************%@",loginUserId);
    [manger.requestSerializer setValue:loginUserId forHTTPHeaderField:@"user.login.id"];

     //[manger.requestSerializer setValue:@"65069F4357BA7A84CC7D865B537FD2DA6A7EA7E24ED05D39D4C6BA1FEAEFEEAB38AACD86384CC1FF" forHTTPHeaderField:@"loginUserId"];
    
//        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//        NSString *loginUserId =  [userDefaults objectForKey:UserHeader];
      // NSLog(@"*************************%@",loginUserId);
    
    
    // 3.发送请求
    [manger POST:str parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
    
}

@end


在控制器里面写请求数据方法  然后调用

-(void)request{
NSMutableDictionary *params = [NSMutableDictionary dictionary];

    long para = [self.freeID integerValue];
    DLog(@"%ld",para);
    params[@"spm"] = @(para);
    
       // 网络请求
    [MSHttpRequest post:@"/api/freeOrder/userOrderDetail.json"params:params success:^(id json) {
        DLog(@"%@",json);
    } failure:^(NSError *error) {
        DLog(@"订单详情请求失败%@",error);
    }];
}


你可能感兴趣的:(AFNetworking,post请求)