iOS-AFNETWORKING 2.0 -AFHTTPRequestOperationManager - POST-MULTIPART-REQUEST

时间:2013-11-04 11:22:34

标签: objective-c ios7 afnetworking-2 afhttprequestoperation

我已经构建了一个用于与我的Web服务器通信的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并且我的请求serilaizer设置为AFJSONRequestSerializer,也不会创建JSON对象。 同样,这只发生在POST MULTIPART上,其他使用相同客户端和设置完成的请求都会正确处理。

谢谢!

3 个答案:

答案 0 :(得分:1)

服务器正在回复status code 500的响应,这意味着您的服务器在尝试处理请求时遇到错误。你如何使用AFNetworking似乎没有任何问题,但唯一的方法就是首先在服务器端进行调试。

答案 1 :(得分: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;
}

答案 2 :(得分:0)

我在Rails 3.1上遇到了类似的东西,升级到3.2解决了它。