使用YTNetwork 处理POST请求,老是出错,状态码400, 为什么啊?

邓轻舟
  • 384

业务测试代码:使用官方推荐的模式

   @implementation AddressCreateAPI{
        
         //···  
        }
 - (instancetype)initWithDefaultFlag:(NSNumber *)defaultFlag address:(NSString *)address recipientMobile:(NSString
    *)recipientMobile recipientName: (NSString *) recipientName districtCode: (NSString *) districtCode cityCode: (NSString *)cityCode provinceCode: (NSString *)provinceCode {
        self = [super init];
        if (self) { 
        //···
        }
        return self; }
    
    
    
    - (NSString *)requestUrl {
        return @"v1/addresses";
        //kAddressCreate; }
    
    - (YTKRequestMethod)requestMethod{
        return YTKRequestMethodPOST; }
    
    
    - (id)requestArgument {
    
        return  @{
            @"address": @"string",
            @"cityCode": @"110100",
             @"defaultFlag": @YES,
             @"districtCode": @"110101",
             @"provinceCode": @"110000",
             @"recipientMobile": @"15921817853",
             @"recipientName": @"string"
            }; }
        
        
        
        - (NSDictionary<NSString *,NSString *> *)requestHeaderFieldValueDictionary{
            NSString * tokenStr = [NSString stringWithFormat: @"Bearer %@", [MainAccountModel shareMainAccountModel ].authorization ];
            return @{@"Authorization": tokenStr }; }
检查YTKNetwork的源码,请求头、 url、 参数、 API 方法,均无误。

- (NSURLSessionTask *)sessionTaskForRequest:(YTKBaseRequest *)request error:(NSError * _Nullable __autoreleasing *)error {
    YTKRequestMethod method = [request requestMethod];           // 查看调用方法, POST
    NSString *url = [self buildRequestUrl:request];  // 查看 URL
    id param = request.requestArgument;   // 查看 参数
    AFConstructingBlock constructingBlock = [request constructingBodyBlock];
    AFHTTPRequestSerializer *requestSerializer = [self requestSerializerForRequest:request];

    switch (method) {
        case YTKRequestMethodGET:
            if (request.resumableDownloadPath) {
                return [self downloadTaskWithDownloadPath:request.resumableDownloadPath requestSerializer:requestSerializer URLString:url parameters:param progress:request.resumableDownloadProgressBlock error:error];
            } else {
                return [self dataTaskWithHTTPMethod:@"GET" requestSerializer:requestSerializer URLString:url parameters:param error:error];
            }
        case YTKRequestMethodPOST:
            return [self dataTaskWithHTTPMethod:@"POST" requestSerializer:requestSerializer URLString:url parameters:param constructingBodyWithBlock:constructingBlock error:error];
            ··· 



- (AFHTTPRequestSerializer *)requestSerializerForRequest:(YTKBaseRequest *)request {
    AFHTTPRequestSerializer *requestSerializer = nil;
    //···

    // If api needs to add custom value to HTTPHeaderField
    NSDictionary<NSString *, NSString *> *headerFieldValueDictionary = [request requestHeaderFieldValueDictionary];
    if (headerFieldValueDictionary != nil) {
        for (NSString *httpHeaderField in headerFieldValueDictionary.allKeys) {
            NSString *value = headerFieldValueDictionary[httpHeaderField];
            [requestSerializer setValue:value forHTTPHeaderField:httpHeaderField];   // 查看请求头
        }
    }
    return requestSerializer; }

然后在YTKNetwork中,查看状态码, 返回 400

- (BOOL)statusCodeValidator {
    NSInteger statusCode = [self responseStatusCode];  // 返回400
    return (statusCode >= 200 && statusCode <= 299);
}

使用官方推荐的 buildCustomUrlRequest, 还是 400. 业务测试代码:

- (NSURLRequest *)buildCustomUrlRequest{
    NSString * urlStr = [NSString stringWithFormat: @"%@%@",kCHBaseUrl, kAddressCreate  ];
    NSMutableURLRequest * mutableRequest = [[NSMutableURLRequest alloc ] initWithURL: [NSURL URLWithString: urlStr] cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 60.0];
    [mutableRequest setHTTPMethod:@"POST"];
    NSString * tokenStr = [NSString stringWithFormat: @"Bearer %@",[MainAccountModel shareMainAccountModel ].authorization ];
    [mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [mutableRequest setValue: tokenStr forHTTPHeaderField: @"Authorization" ];
    NSDictionary * arguDict = @{
                                @"address": @"string",
                                @"cityCode": @"110100",
                                @"defaultFlag": @YES,
                                @"districtCode": @"110101",
                                @"provinceCode": @"110000",
                                @"recipientMobile": @"15921811111",
                                @"recipientName": @"string"
                                };
    NSMutableString * jsonStr = [[NSMutableString alloc ] initWithCapacity: 220 ];
    NSInteger i = 0;
    for (NSString * everyKey in arguDict.allKeys) {
        [jsonStr appendFormat: @"%@=%@", everyKey, arguDict[everyKey] ];
        if(i != arguDict.allKeys.count - 1){
            [jsonStr appendString: @"&" ];
        }
        i++;
    }
    [mutableRequest setHTTPBody: [ jsonStr dataUsingEncoding: NSUTF8StringEncoding  ] ];

    return mutableRequest;
}
@end

使用AFN, OK.
代码:


[GetNetWorkDataMethod networkRequest: arguDictionary requestType: ZheNetworkingRequestTypePost andWithURLStr: kAddressCreate success:^(NSURLSessionDataTask *task, NSDictionary *responseObject) {
    //responseObject;
    [[NSOperationQueue mainQueue ] addOperationWithBlock:^{
        [wSelf.navigationController popViewControllerAnimated: YES ];
        [CHUtil showHubWithStr: @"用户地址保存成功" withView: nil ];
    } ];
    
} exception:^(NSDictionary *responseObject) {
    
} failure:^(NSError *error) {
    //error;
    [CHUtil showHubWithStr: @"用户收货地址数量达到5个,无法继续添加!" withView: self.view];
} ];

回复
阅读 4.3k
4 个回答

我设置了一下这个,就好了:

- (YTKRequestSerializerType)requestSerializerType{
    return YTKRequestSerializerTypeJSON;
}

请求错误,你可以用Charles抓一下包看看你的URL和参数到底对没对。

嗯,我对这个不清楚,不过你为什么不把请求抓下来对比下哪里不一样呢?

先查400代表什么,再排查可能性

你知道吗?

宣传栏