AFHTTPRequest结果为null(即使我在浏览器中可以看到JSON)

时间:2013-06-06 18:30:35

标签: java ios afhttpclient

我正在使用GET请求来获取JSON数据。

电话看起来像这样:

-(void)getJSON{

    //Where request is going
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://localhost:1234"]];

    //Parameters
    NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET"
                                                            path:@"/test"
                                                      parameters:nil];

    //Init operation
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];

    //Set completion block
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        //Handle response
        NSLog(@"Request succesful");

        NSLog(@"Response: %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);


    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        //Code to execute if failed
        NSLog(@"Error: %@", error);
    }];

    //Initiate request
    [operation start];

}

当我在浏览器上查询时,我得到了这个:

{"Object 2":"Lemon","Object 1":"Chicken"} //http://localhost:1234/test

此响应由我的方法在服务器上发送(在java中):

/**
     * Sends reply back to client
     * @throws Exception
     */
    private void sendResponse() throws Exception{

        HashMap<String, String> mapResponse = new HashMap<String, String>();
        mapResponse.put("Object 1", "Chicken");
        mapResponse.put("Object 2", "Lemon");

        //Convert to JSON
        Gson gson = new Gson();
        String json = gson.toJson(mapResponse);

        //write out as JSON
        responseToClient.writeBytes(json);
    }

不确定为什么xcode没有处理响应... 当我查看调试器中的值时,它表示responseObject = x0000000(null)

enter image description here

1 个答案:

答案 0 :(得分:1)

发回数据时添加HTTP响应标头。至少Content-Type,最好还包括Content-Length。这将允许AF类了解如何处理接收的数据。

相关问题