javaiosafhttpclient

AFHTTPRequest result null (even though I can see JSON in browser)


I am using a GET request to get JSON data.

The call looks like this:

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

}

When I query on my browser I get this:

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

This response is sent by my method on the server (in 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);
    }

Not sure why xcode isn't handling the response... When I look at the value in the debugger it says responseObject = x0000000 (null)

enter image description here


Solution

  • Add HTTP response headers when you send back the data. At least Content-Type and, preferably, also include Content-Length. This will allow the AF classes to understand what to do with the received data.