【问题标题】:Getting server error message while parsing json using NSURLConnection in Objective C在Objective C中使用NSURLConnection解析json时获取服务器错误消息
【发布时间】:2019-01-06 10:12:53
【问题描述】:
[
{
    "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;
}

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

谢谢....

【问题讨论】:

  • 除此问题外,请勿使用同步 URL 请求。 sendSynchronousRequest 已被弃用很长时间。
  • 你有什么错误?
  • 我收到错误消息 = "发生错误。";

标签: objective-c arrays json xcode nsurlconnection


【解决方案1】:

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

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

【讨论】:

  • 我已经添加了这条线,但一点运气都没有
  • 您能说出您使用的是哪种类型的编码吗?你在哪里添加这行代码?
  • NSMutableURLRequest *requestURL = [NSMutableURLRequest requestWithURL:adUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:900.00]; NSLog(@"%@",requestURL); [requestURL setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [requestURL setHTTPMethod:@"POST"]; NSError *error=nil ; if ([参数 isKindOfClass : [NSString class]]) { [requestURL setHTTPBody:[参数 dataUsingEncoding:NSUTF8StringEncoding]]; }
  • 你能检查一下哪个 if() 条件有效,然后在 Postman 中获取参数并检查它。
  • 如果页面需要 JSON,它可能希望内容类型为 JSON,而不是 URL 编码字段。我的意思是,我猜一个页面可以在单个字段中使用 JSON,但这有点奇怪。
【解决方案2】:

我使用这条线,对我来说就像魔法一样工作

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

【讨论】:

    猜你喜欢
    • 2011-10-24
    • 2023-04-07
    • 1970-01-01
    • 2017-07-03
    • 2022-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多