Objective C NSMutableURLRequest GET请求返回null JSON

时间:2014-02-17 11:21:15

标签: objective-c json get nsjsonserialization nsmutableurlrequest

尝试使用@“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);


}

4 个答案:

答案 0 :(得分:3)

如果您想使用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"];

答案 1 :(得分:1)

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

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

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

答案 2 :(得分:0)

你似乎在GET和POST之间感到困惑。你正在进行GET,但提供像POST这样的数据(虽然没有强制要求,或者排除了使用正文数据进行GET)。

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

这完全取决于服务器期望(并且可以处理)。这是你需要知道和匹配...


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

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

答案 3 :(得分:0)

我发现了我的问题:

发送paramString使用“Get”方法,不能在字母之间发送带空格的参数。例如:“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);


}

谢谢大家!