gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:52:07 26 4
gpt4 key购买 nike

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

最佳答案

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

关于java - AFHTTPRequest 结果为空(即使我可以在浏览器中看到 JSON),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16969532/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com