【问题标题】:AFHTTPRequest result null (even though I can see JSON in browser)AFHTTPRequest 结果为空(即使我可以在浏览器中看到 JSON)
【发布时间】:2013-06-06 18:30:34
【问题描述】:

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

【问题讨论】:

  • 什么是零?您是否询问过操作以获取响应/状态码/内容类型?
  • 如果我断点第一个 NSLog 响应对象没有分配内存(它说 x0000000)=null
  • 所以询问响应(operation.response)
  • 它说
  • 信息量很大。在调试器中,输入“p [[操作响应] statusCode]”,然后输入 po [[操作响应] allHeaderFields]'。这些将为您提供有关响应内容的详细信息...

标签: java ios afhttpclient


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-05-28
    • 2023-04-02
    • 1970-01-01
    • 2015-12-04
    • 1970-01-01
    • 2017-10-01
    • 2019-04-17
    • 2019-07-29
    • 1970-01-01
    相关资源
    最近更新 更多