简体   繁体   English

在目标C中使用NSURLConnection解析JSON时获取服务器错误消息

[英]Getting server error message while parsing json using NSURLConnection in Objective C

[
{
    "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

}
]

This is my json format populated from the app and I am sending it to server in a post method to get a desired json result. 这是从应用程序填充的json格式,我将其以post方法发送到服务器以获取所需的json结果。 But the server is providing me an unknown error. 但是服务器向我提供了一个未知错误。 But it is working in Postman as well Here I convert my array of dictionary to json 但是它也可以在邮递员中工作这里我将字典数组转换为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]];

Here orderArray is my array of dictionary and my parsing code is provided below 这里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;
}

I didn't find any coding or logical error from my side. 我没有发现任何编码或逻辑错误。 I have used this code several times and it worked fine. 我已经多次使用此代码,并且效果很好。 Is there any settings are permission required in the app side? 应用程序端需要权限设置吗?

Thanks .... 谢谢 ....

You said that its working fine in Postman, you should check if the request in to send in form-url encoded formate. 您说它在Postman中工作正常,您应该检查请求是否以表单URL编码的形式发送。 If it is, you should add the following line 如果是,则应添加以下行

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

我用这条线对我来说就像魔术一样

 [requestURL setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM