2013-11-04 92 views
2

我已經建立了一個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,其他請求使用相同的客戶端和設置完成,正確處理。

謝謝!

回答

1

服務器發送迴應status code 500,這意味着您的服務器在嘗試處理請求時遇到錯誤。您使用AFNetworking的方式似乎沒有任何問題,但唯一的辦法是首先在服務器端調試事情。

1

自從我解決了這個問題已經有一段時間了,但也許這仍然可以幫助某人。最後,就我而言,上層httpPOSTMultiPartRequestWithPath方法沒有被削減,我需要更多的消息結構靈活性(例如,設置自定義邊界)。我結束了使用HTTPRequestOperationWithRequest方法並手動創建了URLrequest。

-(void)httpPOSTmultipartContentWithPath:(NSString*)path Parameters:(NSDictionary*)parameters Body:(NSData*)body Completion:(APICompletionBlock)apiComp{ 

    NSURL *pathURL = [NSURL URLWithString:path]; 
    NSURLRequest *request = [self POSTRequestWithURL:pathURL DataDictionary:parameters andBody:body]; 

    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request 
                     success:^(AFHTTPRequestOperation *operation, id responseObject) { 
                      apiComp(responseObject,nil); 
                     } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
                      apiComp(nil,error); 
                     }]; 

    [operation start]; 
} 

- (NSMutableURLRequest *)POSTRequestWithURL:(NSURL *)url DataDictionary:(NSDictionary *)dictionary andBody:(NSData*)body 
{ 

    // Create a POST request 
    NSMutableURLRequest *myMedRequest = [NSMutableURLRequest requestWithURL:url]; 
    [myMedRequest setHTTPMethod:@"POST"]; 

    // Add HTTP header info 

    NSString *boundary = @"*****"; 
    NSString *lineEnd = @"\r\n"; 
    NSString *twoHyphens = @"--"; 
    [myMedRequest addValue:[NSString stringWithFormat:@"multipart/form-data;boundary= %@", boundary] forHTTPHeaderField:@"Content-Type"]; 

    //create HTTP Body 
    NSMutableData *POSTBody = [NSMutableData data]; 
    [POSTBody appendData:[[NSString stringWithFormat:@"boundary=%@%@%@",twoHyphens,boundary,lineEnd] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [POSTBody appendData:[[NSString stringWithFormat:@"Content-Type:multipart/related;type=application/json;boundary=%@%@%@%@",twoHyphens,twoHyphens,boundary,lineEnd] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [POSTBody appendData:[[NSString stringWithFormat:@"Content-Id:jsonTemp%@",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [POSTBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"json\"%@%@", lineEnd,lineEnd] dataUsingEncoding:NSUTF8StringEncoding]]; 
    //add JSON dictionary with request inforamtion 
    [POSTBody appendData:[[NSString stringWithFormat:@"%@%@",dictionary 
    ,lineEnd] dataUsingEncoding:NSUTF8StringEncoding]]; 

    [POSTBody appendData:[lineEnd dataUsingEncoding:NSUTF8StringEncoding]]; 
    [POSTBody appendData:[[NSString stringWithFormat:@"%@%@%@",twoHyphens,boundary,lineEnd] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [POSTBody appendData:[[NSString stringWithFormat:@"Content-Type:image/jpg"] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [POSTBody appendData:[[NSString stringWithFormat:@"%@",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [POSTBody appendData:[[NSString stringWithFormat:@"Content-Id:%@",@"profile.jpg"] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [POSTBody appendData:[[NSString stringWithFormat:@"%@",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [POSTBody appendData:[[NSString stringWithFormat:@"%@",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]]; 

    // Add image data 
    [POSTBody appendData:body]; 


    // Add the closing -- to the POST Form 
    [POSTBody appendData:[[NSString stringWithFormat:@"%@",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [POSTBody appendData:[[NSString stringWithFormat:@"%@%@%@%@",twoHyphens,boundary,twoHyphens, lineEnd] dataUsingEncoding:NSUTF8StringEncoding]]; 


    // Add the body to the myMedRequest & return 
    [myMedRequest setHTTPBody:POSTBody]; 
    return myMedRequest; 
} 
0

我在Rails 3.1上遇到類似的問題,升級到3.2就解決了我的問題。