0

我正在使用 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)

在此处输入图像描述

4

1 回答 1

1

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

于 2013-06-06T19:33:07.060 回答