AFNetworking 2.0 : Cannot POST with JSON from IOS

﹥>﹥吖頭↗ 提交于 2019-12-05 08:01:40

Actually, I finally got it to work.

Basically, for my requestSerializer of the AFHTTPRequestOperationManager, I was using AFHTTPRequestSerializer and then trying to set the Content-Type to "application/json"

But once I switched to using AFJSONRequestSerializer instead, it works fine now

AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];

[requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];

operationManagerInstance.requestSerializer = requestSerializer;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[serializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
manager.requestSerializer = serializer;

now it will work.

I encountered the same problem using AFNetworking API through Swift, trying to send a post request and finally got it work as well thanks to user1805458's post.

Basically, for my requestSerializer of the AFHTTPRequestOperationManager, I was also using AFHTTPRequestSerializer and then trying to set the Content-Type to "Application/JSON" and it did not work.

But once I switched to using AFJSONRequestSerializer instead, it works fine now:

        let manager = AFHTTPRequestOperationManager()
        manager.requestSerializer = AFJSONRequestSerializer(writingOptions: nil)

        // Contrary to user1805458's solution, I did not need to use these two instructions below using Swift.
        // manager.requestSerializer.setValue("Application/JSON", forHTTPHeaderField:"Content-Type")
        // manager.requestSerializer.setValue("Application/JSON", forHTTPHeaderField:"Accept")

I hope it will help you to fix this error in case where you use Swift, AFNetworking and try to send a post request containing a JSON body.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!