AFNetworking 返回错误unsupported media type (415) 解决方案

来源:互联网 发布:c语言编程界面 编辑:程序博客网 时间:2024/04/24 04:15

这篇博客,是从其他博客那里抄来的!
来源:http://blog.csdn.net/whoten/article/details/21537211

http://stackoverflow.com/questions/21152847/how-to-post-data-using-afnetworking-2-0
从这里可以知道:
AFNetwoking的默认Content-Type是application/x-www-form-urlencodem。若服务器要求Content-Type为applicaiton/json,为了和服务器对应,就必须修改AFNetworking的Content-Type。

关于Content-Type的概念和Post常见的的提交数据方式请见博客:https://www.imququ.com/post/four-ways-to-post-data-in-http.html。

简单来说,服务器通过识别Content-Type来识别传送的数据类型,分辨传送的数据到底是文本,图片或者是其他。如果服务器不识别对应的Content-Type,那么就会返回错误415.

修改Content-Type代码如下:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];  manager.requestSerializer = [AFJSONRequestSerializer serializer];  [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];  
 修改后便可正常使用如下方法进行POST访问了,GET访问查看头文件选择对应方法即可:
- (AFHTTPRequestOperation *)POST:(NSString *)URLString                        parameters:(NSDictionary *)parameters                           success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success                           failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
0 0