简体   繁体   中英

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. 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

 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

 -(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. 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"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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