我已經建立了一個API客戶端與我的網絡服務器,並在我的應用程序的所有HTTP請求的通信使用這個類完成:(AFHTTPRequestOperationManager的子類)iOS- AFNETWORKING 2.0 -AFHTTPRequestOperationManager - POST-MULTIPART-REQUEST
+ (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,其他請求使用相同的客戶端和設置完成,正確處理。
謝謝!