我已经构建了一个 API 客户端来与我的网络服务器进行通信,并且我的应用程序中的所有 HTTP 请求都是使用这个类完成的:(AFHTTPRequestOperationManager 的子类)
+ (SNPAPIClient *)sharedClient {
static SNPAPIClient *_sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURL *baseURL = [NSURL URLWithString:BASE_URL];
_sharedClient = [[SNPAPIClient alloc] initWithBaseURL:baseURL];
_sharedClient.responseSerializer = [AFJSONResponseSerializer serializer];
_sharedClient.requestSerializer = [AFJSONRequestSerializer serializer];
});
return _sharedClient;
}
该类有 3 种 POST、GET 和 POST-MULTIPART 方法。虽然 POST 和 GET 方法可以完美运行,但我在使用 POST-MULTIPART 时遇到了问题。
-(void)httpPOSTMultiPartRequestWithPath:(NSString*)path Parameters:(NSDictionary*)parameters BodyBlock:(id)bodyBlock Completion:(APICompletionBlock)apiComp{
comp = apiComp;
[self POST:path
parameters:parameters
constructingBodyWithBlock:bodyBlock
success:^(NSURLSessionDataTask *task, id responseObject) {
comp(responseObject,nil);
}
failure:^(NSURLSessionDataTask *task, NSError *error) {
comp(nil,error);
}];
}
具体来说,我正在尝试向服务器发送一个简单的 JSON,然后是一个图像。我试过做这样的事情:
从我的控制器我打电话:
NSDictionary *POSTpic = [NSDictionary dictionaryWithObjectsAndKeys:@"109",@"userId",@"P",@"contentType", nil];
NSURL *pictuePath = [NSURL fileURLWithPath:@"cat.JPG"];
[[SNPAPIClient sharedClient]httpPOSTMultiPartRequestWithPath:@"PATH_GOES_HERE"
Parameters:POSTpic
BodyBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:pictuePath name:@"profile" error:nil];
}
Completion:^(id serverResponse, NSError *error){
if (serverResponse){
NSLog(@"success");
}else{
NSLog(@"error: %@",error);
}
}];
发送此请求我在调试器中收到以下错误:
internal server error (500)" UserInfo=0xb681650 {NSErrorFailingURLKey=http://"my_path", AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0xb347d40> { URL: http://"my_path" } { status code: 500, headers {
"Content-Length" = 142;
"Content-Type" = "text/plain";
Date = "Wed, 06 Nov 2013 19:26:05 GMT";
"Proxy-Connection" = "Keep-alive";
Server = "nginx admin";
} }, NSLocalizedDescription=Request failed: internal server error (500)}
出于某种原因,即使我发送了一个 NSDictionary 并且我的请求序列化器设置为 AFJSONRequestSerializer,也不会创建 JSON 对象。同样,这只发生在 POST MULTIPART 中,使用相同客户端和设置完成的其他请求会被正确处理。
谢谢!