POST網(wǎng)絡(luò)請(qǐng)求

用 AFNetworking 通過 POST 方式發(fā)送數(shù)據(jù)

BY 子非魚 · 2014 年 5 月 26 日

AFNetworking進(jìn)行POST請(qǐng)求中 發(fā)送json數(shù)據(jù)有些特別 。

AFNetworking 版本為 2.0.2

POST 發(fā)送數(shù)據(jù)有兩種形式:

1、發(fā)送純文本的內(nèi)容

2、發(fā)送的 body 部分帶有文件(圖片,音頻或者其他二進(jìn)制數(shù)據(jù))

對(duì)應(yīng)的 Content-Type 有兩種:

1、application/x-www-form-urlencoded

2、multipart/form-data

傳統(tǒng)的使用 POST 的方式發(fā)送數(shù)據(jù)用于上傳文件,AFNetworking 中提供了直接的接口:

[self.manager POST:post_url parameters:params

constructingBodyWithBlock:^(id formData) {

// 直接以 key value 的形式向 formData 中追加二進(jìn)制數(shù)據(jù)

[formData appendPartWithFormData:[str dataUsingEncoding:NSUTF8StringEncoding]

name:@"key1"];

[formData appendPartWithFileData:imgData name:@"imagefile"

fileName:@"img.jpg" mimeType:@"image/jpeg"];

}

success:^(AFHTTPRequestOperation *operation, id responseObject) {

// 成功后的處理

}

failure:^(AFHTTPRequestOperation *operation, NSError *error) {

// 失敗后的處理

}];

使用 POST 方式發(fā)送純文本內(nèi)容:

- (NSMutableURLRequest *)postRequestWithURL:(NSString *)url content:(NSString *)text

{

NSMutableURLRequest *request =

[[NSMutableURLRequest alloc] initWithURL:url];

[request setHTTPMethod:@"POST"];

[request setValue:@"application/x-www-form-urlencoded"

forHTTPHeaderField:@"Contsetent-Type"];

[request setHTTPBody:1];

return request;

}

NSOperation *operation =

[self.manager HTTPRequestOperationWithRequest:request

success:^(AFHTTPRequestOperation *operation, id responseObject) {

// 成功后的處理

}

failure:^(AFHTTPRequestOperation *operation, NSError *error) {

// 失敗后的處理

}];

[self.manager.operationQueue addOperation:operation];

其中 self.manager 為 AFHTTPRequestOperationManager 實(shí)例。

_manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url];

// 對(duì)于網(wǎng)站成功返回 JSON 格式的數(shù)據(jù)但是卻在 failure 回調(diào)中顯示的,

// 是因?yàn)榉?wù)器返回?cái)?shù)據(jù)的網(wǎng)頁中 content type 沒有設(shè)置為 text/json

// 對(duì)于我們公司的服務(wù)器返回的 content type 為 text/html 所以我設(shè)置為如下這樣,

// 對(duì)于不同的情況可以根據(jù)自己的情況設(shè)置合適的接受的 content type 的類型

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

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

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

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