AFNetworking2

===================================================
// 1.获得请求管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];

// 2.封装请求参数
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"userId"] = [appDefault objectForKey:@"userId"];
params[@"IMSI"] = _IMSI.text;
params[@"nickName"] = _nickName.text;
params[@"phoneNumber"] = _phoneNumber.text;

NSString *url = [ServiceInfo stringByAppendingString:@"http://103.238.80.57:8080/Vietnam/Application/bindingDevice"];

// 3.发送GET请求
[mgr GET:url parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
     NSLog(@"%@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     NSLog(@"%@",error);
}];

POST:

  • (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
    parameters:(nullable id)parameters
    success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
    failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE;

// 1.获得请求管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];

// 2.封装请求参数
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"userId"] = [appDefault objectForKey:@"userId"];
params[@"IMSI"] = _IMSI.text;
params[@"nickName"] = _nickName.text;
params[@"phoneNumber"] = _phoneNumber.text;

NSString *url = [ServiceInfo stringByAppendingString:@"http://103.238.80.57:8080/Vietnam/Application/bindingDevice"];

// 3.发送GET请求
[mgr POST:url parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
     NSLog(@"%@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     NSLog(@"%@",error);
}];

值得注意的是,AFNetworking默认是使用JSON格式发送和响应返回来的数据的,如果返回来的数据不是JSON,就需要设置一下请求管理者,下面请看代码:

// 1.获得请求管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];

// 因为传递过去和接收回来的数据都不是json类型的,所以在这里要设置为AFHTTPRequestSerializer和AFHTTPResponseSerializer
mgr.requestSerializer = [AFHTTPRequestSerializer serializer];// 请求
mgr.responseSerializer = [AFHTTPResponseSerializer serializer];// 响应

// 2.封装请求参数
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"userId"] = [appDefault objectForKey:@"userId"];
params[@"IMSI"] = _IMSI.text;
params[@"nickName"] = _nickName.text;
params[@"phoneNumber"] = _phoneNumber.text;

NSString *url = [ServiceInfo stringByAppendingString:@"http://103.238.80.57:8080/Vietnam/Application/bindingDevice"];

// 3.发送GET请求
[mgr GET:url parameters:params
 success:^(AFHTTPRequestOperation *operation, id responseObject) {
        // 转码,如果返回的数据不是JSON,这里必须要转码
        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

        NSLog(@"%@",string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
}];

你可能感兴趣的:(AFNetworking2)