首页 > 解决方案 > 在Objective C中使用NSURLConnection解析json时获取服务器错误消息

问题描述

[
{
    "CouponQtn":1,
    "DeliveryDist":14,
    "Sizes":"not selected",
    "CustomerAlternateMobile":"01700790900",
    "deliveryCharge":0,
    "DealId":744706,
    "PaymentType":"MPD",
    "OrderFrom":"ios",
    "CardType":"Manual",
    "OrderSource":"app",
    "CustomerId":630142,
    "MerchantId":15196,
    "AdvPaymentType":0,
    "CustomerBillingAddress":"Khulna",
    "CustomerMobile":"01700790900",
    "Color":"",
    "AdvPayPhoneId":0,
    "OrderCouponPrice":375

}
]

这是我从应用程序填充的 json 格式,我以 post 方法将其发送到服务器以获得所需的 json 结果。但是服务器向我提供了一个未知错误。但它也在 Postman 中工作在这里我将我的字典数组转换为 json

 NSData *jsonData = [NSJSONSerialization dataWithJSONObject:orderArray
                                                                                   options:kNilOptions
                                                                                     error:nil];
                                NSString*jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

                               //NSString* jsonStr = [NSString stringWithUTF8String:[jsonData bytes]];


                                tempDic = [apiCom getNodeDataByPOST:CART_ORDER_URL parameter:[NSString stringWithFormat:@"%@",jsonStr]];

这里 orderArray 是我的字典数组,下面提供了我的解析代码

 -(NSDictionary*)getNodeDataByPOST:(NSString*)url parameter:(id)parameter{

    NSDictionary *dictionaryData;
    NSDictionary *dic;
    Reachability *reachTest = [Reachability reachabilityWithHostName:@"www.apple.com"];
    NetworkStatus internetStatus = [reachTest  currentReachabilityStatus];
    if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)){
        dictionaryData = [[NSDictionary alloc] initWithObjectsAndKeys:@"error",@"status",@"No Network",@"message",nil];
        dic = [NSDictionary dictionaryWithObjectsAndKeys:dictionaryData, @"response",nil];
        return dic;
    }

    else{
        NSURL *adUrl =[NSURL URLWithString:url];

        NSMutableURLRequest *requestURL = [NSMutableURLRequest requestWithURL:adUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:900.00];
        //NSLog(@"%@",requestURL);
        [requestURL setHTTPMethod:@"POST"];


        NSError *error=nil ;
        if ([parameter isKindOfClass : [NSString class]]) {
           [requestURL setHTTPBody:[parameter dataUsingEncoding:NSUTF8StringEncoding]];


        }
//        else if([parameter isKindOfClass:[NSDictionary class]]) {
//            [requestURL setHTTPBody:parameter];
//        }
        else if([parameter isKindOfClass:[NSArray class]]||[parameter isKindOfClass:[NSDictionary class]]) {
            [requestURL setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameter options:0 error:nil]];

        }
        else {
            [requestURL setHTTPBody:parameter];
        }
        NSHTTPURLResponse *response;
        NSError *error1=nil;
        //        NSLog(@"%@\n\n%@",s,parameter);
        NSData *apiData = [NSURLConnection sendSynchronousRequest:requestURL returningResponse:&response error:&error1];

        if (!apiData) {
            NSLog(@"Error: %@", [error localizedDescription]);

        }

        if (response.statusCode == 0) {

            dictionaryData = [[NSDictionary alloc] initWithObjectsAndKeys:@"error",@"status",@"Server Error",@"message",nil];
            return dic;

        }
        else if(response.statusCode == 404) {
            dictionaryData= [[NSDictionary alloc] initWithObjectsAndKeys:@"error",@"status",@"Server is Currently Down.",@"message", nil];
            return dic;

        }
        else {
            dictionaryData = [NSJSONSerialization JSONObjectWithData:apiData options:kNilOptions error:&error];


        }
    }
    return dictionaryData;
}

我没有发现任何编码或逻辑错误。我已经多次使用此代码并且效果很好。应用端是否需要任何设置权限?

谢谢 ....

标签: objective-carraysjsonxcodensurlconnection

解决方案


您说它在 Postman 中工作正常,您应该检查请求是否以 form-url 编码的格式发送。如果是,则应添加以下行

       [requestURL setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

推荐阅读