IOS AFNetWorking 通過body傳遞參數給服務器

post請求體封裝如下:

- (void)postWithUrl:(NSString *)url body:(NSData *)body? success:(void(^)(NSDictionary *response))success failure:(void(^)(NSError *error))failur

{

NSString *requestUrl = @“”;

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

//如果你不需要將通過body傳 那就參數放入parameters里面

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:requestUrl parameters:nil error:nil];

NSLog(@"requestURL:%@",requestUrl);

request.timeoutInterval= 10;

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

// 設置body 在這里將參數放入到body

[request setHTTPBody:body];

AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];

responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",

@"text/html",

@"text/json",

@"text/javascript",

@"text/plain",

nil];

manager.responseSerializer = responseSerializer;

[[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse *response,id responseObject,NSError *error){

if(responseObject!=nil){

success(responseObject);

}

if (error) {

failure(error);

}

}]resume];

}


調用:

NSDictionary *dict = @{@"name":@"hello",@"sex":@"男"};

NSData *data =? ? [NSJSONSerialization dataWithJSONObject:dict options:NSUTF8StringEncoding error:nil];

[self postWithUrl:@"" body:data showLoading:0 success:^(NSDictionary *response) {

//NSString *result = [[NSString alloc] initWithData:response? encoding:NSUTF8StringEncoding];

NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:nil];? //解析

NSLog(@"%@",result);

} failure:^(NSError *error) {

}];

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容