AFNetworking3.0的使用


POST请求

// 请求的参数

```

NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"20131129", @"date", @"1", @"startRecord", @"5", @"len", @"1234567890", @"udid", @"Iphone", @"terminalType", @"213", @"cid", nil];

```


// 初始化Manager

```

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

```

// 不加上这句话,会报“Request failed: unacceptable content-type: text/plain”错误,因为我们要获取text/plain类型数据

```

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

```

# post请求

```

[manager POST:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?" parameters:dic constructingBodyWithBlock:^(id  _Nonnull formData) {

// 拼接data到请求体,这个block的参数是遵守AFMultipartFormData协议的。

} progress:^(NSProgress * _Nonnull uploadProgress) {

// 这里可以获取到目前的数据请求的进度

} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {


// 请求成功,解析数据

NSLog(@"%@", responseObject);

NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];

NSLog(@"%@", dic);

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

// 请求失败

NSLog(@"%@", [error localizedDescription]);

}];

```



#如果是Get请求,相比Post请求,少了请求参数,然后只需将post方法改为get方法[manager 

```

GET:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {

// 这里可以获取到目前的数据请求的进度

} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

// 请求成功,解析数据

NSLog(@"%@", responseObject);

NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];

NSLog(@"%@", dic);

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

// 请求失败

NSLog(@"%@", [error localizedDescription]);

```

}];


注意:不管是Post 还是Get请求 都需要加

```

session.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

```

你可能感兴趣的:(AFNetworking3.0的使用)