【问题标题】:Objective C NSMutableURLRequest GET request returns null JSONObjective C NSMutableURLRequest GET 请求返回空 JSON
【发布时间】:2014-02-17 11:21:14
【问题描述】:

尝试使用@"GET" 请求从服务器获取数据, 以下代码始终返回 null

有人发现我的以下代码有问题吗?

或者它可以是服务器端问题.. ?

感谢您的帮助!

+ (id)sendParam:(NSString*)ParamString url:(NSString*)url{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];


    NSString *post = ParamString;

    NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

    NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];

    [request setURL:[NSURL URLWithString:url]];


    NSLog(@"postLength =%@",postLength);

    [request setHTTPBody:postData];
    [request setHTTPMethod:@"GET"];
    [request addValue:ParamString forHTTPHeaderField:@"GET"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];


    NSURLResponse *response;
    NSError *error;

    NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    NSMutableArray*jsonReturn = [[NSMutableArray alloc]init];
    jsonReturn = (NSMutableArray*)[NSJSONSerialization JSONObjectWithData:aData options:kNilOptions error:&error];
    NSLog(@"jsonReturn %@",jsonReturn);

    return jsonReturn;
}

编辑后:

  + (id)sendParam:(NSString*)ParamString url:(NSString*)url{

    NSString*StringGETMETHOD = [NSString stringWithFormat:@"%@%@",url,ParamString];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
    [request setURL:[NSURL URLWithString:StringGETMETHOD]];
    [request setHTTPMethod:@"POST"];


    NSURLResponse *response;
    NSError *error;

    NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSLog(@"aData=%@",aData);


    if (aData) {

        jsonReturn=(NSMutableArray*)[NSJSONSerialization JSONObjectWithData:aData options:kNilOptions error:&error];

        NSLog(@"jsonReturn %@",jsonReturn);


}

【问题讨论】:

    标签: objective-c json get nsjsonserialization nsmutableurlrequest


    【解决方案1】:

    如果您想使用 GET 从服务器获取响应,您可以尝试以下方法

    //just give your URL instead of my URL
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL  URLWithString:@"http://api.worldweatheronline.com/free/v1/search.ashx?query=London&num_of_results=3&format=json&key=xkq544hkar4m69qujdgujn7w"]];
    
    [request setHTTPMethod:@"GET"];
    
    [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];
    
    NSError *err;
    
    NSURLResponse *response;
    
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request   returningResponse:&response error:&err];
    
     //You need to check response.Once you get the response copy that and paste in ONLINE JSON VIEWER.If you do this clearly you can get the correct results.    
    
     //After that it depends upon the json format whether it is DICTIONARY or ARRAY 
    
    NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
    
    NSArray *array=[[jsonArray objectForKey:@"search_api"]objectForKey:@"result"];
    

    【讨论】:

      【解决方案2】:

      我非常怀疑您是否应该将此参数作为 HEADER 字段发送。 我也认为您应该发送 POST 而不是 GET。

      将 jsonReturn 设置为 [[NSMutableArray alloc] init] 是无稽之谈。向自己解释为什么要这样做,而不是将 jsonReturn 设置为 nil

      记录 jsonReturn 是无稽之谈,因为所有有趣的东西都消失了。您应该记录响应和返回的数据,至少如果 jsonReturn = nil。

      【讨论】:

      • 你的意思是日志应该显示aDataerror(在JSON反序列化之前和之后),是吗?
      • 如果 jsonReturn 不是 nil,那么你知道 http 请求很好,所以不需要记录它。如果 jsonReturn 为 nil,您想知道问题出在 http 还是与返回的数据有关,因此您可能希望记录错误、响应和数据。您需要记录错误和响应,因为“错误”是关于与服务器的通信,而“响应”是关于服务器决定做什么。如果服务器说“你不能得到你要求的数据”,那么就 http 请求而言,这不是错误;它告诉你服务器说了什么,所以它没有错误。
      【解决方案3】:

      您似乎对 GET 和 POST 感到困惑。您正在执行 GET,但提供像 POST 一样的数据(通常会这样做,尽管它不是强制性的,或者被排除在 GET 中使用正文数据)。

      通常,您不希望将正文数据用于 GET,这不常见/不预期,因此可能会发生任何数量的不同问题。要么将 setHTTPMethod: 更改为 @"POST" 以便正确执行 POST,要么将参数更改为请求 URL 的一部分。

      这完全取决于服务器的期望(并且可以处理)。这是您需要了解和匹配的内容...


      随后您遇到了不同的问题。您提供的参数字符串中包含需要编码的字符(如空格)。在发送参数字符串之前使用stringByAddingPercentEscapesUsingEncoding: 来转义这些字符。

      它可以在浏览器中工作,因为它会为您添加转义字符(在加载响应后,您应该在浏览器地址栏中看到)。

      【讨论】:

      • 所以你的意思是我可以使用HTTPMethod @“POST”,而使用“GET”方法的服务器端可以处理它?感谢 Wain 的回复..
      • 不,如果服务器期望获取而不是发布,那么您应该发送一个 GET,但将参数编码为 URL 的一部分,而不是在正文数据中。你在服务器上有错误日志来告诉你它认为什么是错误的吗?
      • 嗨 Wain,请看我上面的编辑代码.. 看起来可以吗? (仍然返回 null),但是将 "POST" string 复制到浏览器,返回结果。
      • [request setHTTPMethod:@"POST"]; 更改为[request setHTTPMethod:@"GET"];。 @user3182143 的回答很好地概述了您应该拥有的代码。
      • 它仍然很奇怪,如果我在浏览器上复制粘贴 URL + 参数字符串,它会返回结果.. 但是像 user3182143 的代码一样从 IOS 端构建请求,返回 null.. http://81.218.79.240/apns/apns.php?task=fetchgames&user_uid=502122107&search_epoc=2014-02-17 12:23:03 +0000&user_city=tel aviv&user_latitude=0.000000&user_longitude=0.000000
      【解决方案4】:

      我发现了我的问题:

      使用“Get”方法发送paramString,不能发送字母之间有空格的参数。例如:“tel aviv”应该是“tel%20aviv”

      通过添加以下代码行:

       **urlParam = [urlParam
                        stringByReplacingOccurrencesOfString:@" " withString:@"%20"];**
      

      修复代码:

       + (id)sendParam:(NSString*)ParamString url:(NSString*)url{
      
          NSString* urlParam = [NSString stringWithFormat:@"%@%@",url,ParamString];
      
       urlParam = [urlParam
                        stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
      
        NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlParam]];
      
          [request setHTTPMethod:@"GET"];
      
          [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];
      
      
      
          NSURLResponse *response;
          NSError *error;
      
          NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
          NSLog(@"aData=%@",aData);
      
      
          if (aData) {
      
              jsonReturn=(NSMutableArray*)[NSJSONSerialization JSONObjectWithData:aData options:kNilOptions error:&error];
      
              NSLog(@"jsonReturn %@",jsonReturn);
      
      
      }
      

      谢谢大家!

      【讨论】:

        猜你喜欢
        • 2015-11-14
        • 2023-04-02
        • 2021-02-03
        • 2021-11-20
        • 1970-01-01
        • 1970-01-01
        • 2015-03-18
        • 2016-07-05
        • 1970-01-01
        相关资源
        最近更新 更多