YTKBaseRequest的requestSerializerType屬性默認(rèn)值是YTKRequestSerializerTypeHTTP思杯,對應(yīng)的Content-Type類型是application/x-www-form-urlencoded,form表單數(shù)據(jù)需要被編碼為key/value格式發(fā)送到后臺(tái)袜香,一般的使用方式如下(以編輯車牌接口為例):
@implementation SCCarParkUpdateCarRelationAPI
- (NSString *)requestUrl
{
return [NSString stringWithFormat:@"carParkApplication/%@/updateCarRelation", self.orderId];
}
- (YTKRequestMethod)requestMethod
{
return YTKRequestMethodPOST;
}
- (id)requestArgument
{
return self.params;
}
- (void)setCarLicenceList:(NSArray *)carLicenceList
{
// 服務(wù)列表信息
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ù)到后臺(tái): 重寫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的實(shí)例
所有NSDictionary的key必須是NSString類型
數(shù)字對象不能是非數(shù)值或無窮
還有一點(diǎn),如果使用MJExtension中的mj_jsonObject把對象轉(zhuǎn)換成json對象時(shí)萌业,必須保證該對象不遵守任何協(xié)議坷襟,不然轉(zhuǎn)換是不成功的,issue請見:https://github.com/CoderMJLee/MJExtension/issues/649
其它注意事項(xiàng):
其它注意事項(xiàng):
1.application/json可使用的http方法有post/put/delete生年。
get操作沒有body部分婴程,只能以key/value形式傳遞參數(shù)拼接在url中
post/put/delete有body部分,與服務(wù)器傳遞信息抱婉,都放在body中
2.是否使用application/json方式進(jìn)行傳值档叔,需要與后臺(tái)約定好
3.可對單個(gè)接口使用application/json方式進(jìn)行傳值桌粉,不影響到其它的接口
4.當(dāng)application/json方式進(jìn)行傳值時(shí),后臺(tái)框架上使用了@RequestBody注解衙四,讀取請求body里面的值直接映射成參數(shù)铃肯,框架完成了這個(gè)事。