YTKBaseRequest的requestSerializerType屬性默認值是YTKRequestSerializerTypeHTTP,對應的Content-Type類型是application/x-www-form-urlencoded,form表單數(shù)據(jù)需要被編碼為key/value格式發(fā)送到后臺,一般的使用方式如下(以編輯車牌接口為例):
@implementation SCCarParkUpdateCarRelationAPI
- (NSString *)requestUrl
{
return [NSString stringWithFormat:@"carParkApplication/%@/updateCarRelation", self.orderId];
}
- (YTKRequestMethod)requestMethod
{
return YTKRequestMethodPOST;
}
- (id)requestArgument
{
return self.params;
}
- (void)setCarLicenceList:(NSArray *)carLicenceList
{
// 服務列表信息
NSData *carLicenceListData = [NSJSONSerialization dataWithJSONObject:carLicenceList options:NSJSONWritingPrettyPrinted error:nil];
NSString *carLicenceListStr = [[NSString alloc] initWithData:carLicenceListData encoding:NSUTF8StringEncoding];
[self.params setValue:carLicenceListStr forKey:@"carLicenceList"];
}
@end
使用json方式發(fā)送數(shù)據(jù)到后臺: 重寫requestSerializerType方法,返回YTKRequestSerializerTypeJSON;然后requestArgument方法直接返回對象即可,如下:
@implementation SCCarParkUpdateCarRelationAPI
- (NSString *)requestUrl
{
return [NSString stringWithFormat:@"carParkApplication/%@/updateCarRelation", self.orderId];
}
- (YTKRequestMethod)requestMethod
{
return YTKRequestMethodPOST;
}
- (id)requestArgument
{
return self.carLicenceList;
}
- (YTKRequestSerializerType)requestSerializerType
{
return YTKRequestSerializerTypeJSON;
}
需要注意的是:
requestArgument方法必須返回能轉(zhuǎn)化成json的對象,要求如下:
頂層對象必須是NSArray或者NSDictionary
所有的對象必須是NSString、NSNumber、NSArray、NSDictionary、NSNull的實例
所有NSDictionary的key必須是NSString類型
數(shù)字對象不能是非數(shù)值或無窮
還有一點,如果使用MJExtension中的mj_jsonObject把對象轉(zhuǎn)換成json對象時,必須保證該對象不遵守任何協(xié)議,不然轉(zhuǎn)換是不成功的,issue請見:https://github.com/CoderMJLee/MJExtension/issues/649
其它注意事項:
其它注意事項:
1.application/json可使用的http方法有post/put/delete。
get操作沒有body部分,只能以key/value形式傳遞參數(shù)拼接在url中
post/put/delete有body部分,與服務器傳遞信息,都放在body中
2.是否使用application/json方式進行傳值,需要與后臺約定好
3.可對單個接口使用application/json方式進行傳值,不影響到其它的接口
4.當application/json方式進行傳值時,后臺框架上使用了@RequestBody注解,讀取請求body里面的值直接映射成參數(shù),框架完成了這個事。