AFNetworking3.0的使用


POST請求

// 請求的參數(shù)

```

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類型數(shù)據(jù)

```

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的參數(shù)是遵守AFMultipartFormData協(xié)議的。

} progress:^(NSProgress * _Nonnull uploadProgress) {

// 這里可以獲取到目前的數(shù)據(jù)請求的進(jìn)度

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


// 請求成功,解析數(shù)據(jù)

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請求,少了請求參數(shù),然后只需將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) {

// 這里可以獲取到目前的數(shù)據(jù)請求的進(jìn)度

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

// 請求成功,解析數(shù)據(jù)

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"];

```

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容