我正在使用AFHTTPRequestOperationManager
来处理POST
请求。现在我故意输入不正确的信息来处理400
错误代码。现在,Web服务实际上返回一个JSON
,其中包含一条消息,向用户解释他们做错了什么。我非常想让这个JSON
在UIAlertView
中显示消息。但是,失败块:
[operationManager POST:ServerURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: Status Code: %d", operation.response.statusCode);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failed: Status Code: %d", operation.response.statusCode);
}];
不传递响应对象,如成功块中的那个。那么有谁知道如何访问Web服务返回的带有400错误的JSON? NSError *error
只给我Request failed: bad request (400)
而不是JSON返回。
任何帮助将不胜感激,˙Mike
答案 0 :(得分:8)
查看- responseObject
的代码,似乎HTTP错误阻止了它的填充。您可以直接抓取responseData
并自行解析,但我会说这是一个错误或一个很好的增强请求。 (在确定是否应该尝试构建响应对象时,看起来- responseObject
可能应该检查self.responseSerializationError
,而不是self.error
。)
答案 1 :(得分:4)
您可以执行以下任一解决方案
1)设置acceptableStatusCodes
接受400 statusCode,然后处理成功块
manager.responseSerializer.acceptableStatusCodes = [NSIndexSet indexSetWithIndex:400];
2)创建一个自定义的ResponseSerializer,就像这个JSONResponseSerializerWithData一样,将responseObject插入到NSError userInfo中,并在失败块中处理
专业提示:AFNetworking是开源,只需看一下AFHTTPRequestOperation的方法
setCompletionBlockWithSuccess:failure:
responseObject
error
答案 2 :(得分:0)
以下代码代表我:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:@"parse-application-id-removed" forHTTPHeaderField:@"X-Parse-Application-Id"];
[manager.requestSerializer setValue:@"parse-rest-api-key-removed" forHTTPHeaderField:@"X-Parse-REST-API-Key"];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
manager.securityPolicy.allowInvalidCertificates = YES;
NSString *URLString = [NSString stringWithFormat:@"%@/%@", BASE_URL,methodName];
[manager POST:URLString parameters:requestDict success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(@"JSON: %@", responseObject);
[myDelegate StopIndicator];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
[myDelegate StopIndicator];
}];
答案 3 :(得分:0)
我在AFNetworking中也面临同样的问题,而不是使用
- (NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(id)parameters
progress:(void (^)(NSProgress * _Nonnull))uploadProgress
success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
请尝试使用那个: -
- (NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(id)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
谢谢,