gpt4 book ai didi

ios - 带有 JSON 主体的 POST 请求 AFNetworking 2.0

转载 作者:可可西里 更新时间:2023-11-01 06:24:24 25 4
gpt4 key购买 nike

是否可以使用 AFNetworking ~> 2.0 发送带有 JSON 正文的 POST 请求?

我试过使用:
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager POST:<url> parameters: @{@"data":@"value"} success: <block> failure: <block>'

但它不起作用。任何帮助是极大的赞赏。谢谢

最佳答案

您可以在 NSMutableURLRequest 中添加您的 JSON 主体,而不是直接在 parameters: 中添加。请参阅我的示例代码:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// Set post method
[request setHTTPMethod:@"POST"];
// Set header to accept JSON request
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
// Your params
NSDictionary *params = @{@"data":@"value"};
// Change your 'params' dictionary to JSON string to set it into HTTP
// body. Dictionary type will be not understanding by request.
NSString *jsonString = [self getJSONStringWithDictionary:params];

// And finally, add it to HTTP body and job done.
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:<block> failure:<block>];

希望对您有所帮助。编码愉快! :)

关于ios - 带有 JSON 主体的 POST 请求 AFNetworking 2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28376975/

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