【问题标题】:POST with URL parameters and JSON body in AFNetworking在 AFNetworking 中使用 URL 参数和 JSON 正文进行 POST
【发布时间】:2014-05-16 02:36:42
【问题描述】:

我想进行一个同时包含 URL 参数和 JSON 正文的 POST 调用:

URL http://example.com/register?apikey=mykey
JSON { "field" : "value"}

如何在 AFNNetworking 中同时使用两个不同的序列化程序?这是我缺少 URL 参数的代码:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:@"http://example.com/register" parameters:json success:^(AFHTTPRequestOperation *operation, id   responseObject) {

【问题讨论】:

    标签: post afnetworking-2


    【解决方案1】:

    我相信没有自动的方法可以做到这一点。但是,有一种简单的手动实现方法:

    - (NSMutableURLRequest *)someRequestWithBaseURL:(NSString *)baseUrl
                                              method:(NSString *)method
                                                path:(NSString *)path
                                          uriParameters:(NSDictionary *)uriParameters
                                      bodyParameters:(NSDictionary *)bodyParameters
    
    NSURL *url = [NSURL URLWithString:path relativeToURL:[NSURL URLWithString:baseUrl]];
    
    AFHTTPRequestSerializer *httpRequestSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:0]
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithDictionary:bodyParameters];
    
    if ([httpRequestSerializer.HTTPMethodsEncodingParametersInURI containsObject:method]) {
        [parameters addEntriesFromDictionary:uriParameters];
    } else {
        NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:YES];
        // For urlEncodedString, check http://stackoverflow.com/a/718480/856549
        urlComponents.percentEncodedQuery = [uriParameters urlEncodedString];
        url = [urlComponents URL];
    }
    
    NSError *error;
    NSURLRequest *request = [httpRequestSerializer requestWithMethod:method
                                                           URLString:[url absoluteString]
                                                          parameters:parameters
                                                               error:&error];
    

    【讨论】:

      【解决方案2】:

      我做一个post方法

      /**
       *  Services gateway
       *  Method  get response from server
       *  @parameter              -> object: request josn object ,apiName: api endpoint
       *  @returm                 -> void
       *  @compilationHandler     -> success: status of api, response: respose from server, error: error handling
       */
      + (void)getDataWithObject:(NSDictionary *)object onAPI:(NSString *)apiName withController:(UIViewController*)controller
                               :(void(^)(BOOL success,id response,NSError *error))compilationHandler {
      
      
          controller = controller;
          [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
      
          AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
      
          // set request type to json
          manager.requestSerializer = [AFJSONRequestSerializer serializer];
          manager.responseSerializer = [AFHTTPResponseSerializer serializer];
      
      
          // post request to server
          [manager POST:apiName parameters:object success:^(AFHTTPRequestOperation *operation, id responseObject) {
      
              // NSError *error;
              NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject
                                                                 options:0
                                                                   error:&error];
      
              //NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
              //// 
      
              // check the status of API
              NSDictionary *dict = responseObject;
              NSString *statusOfApi = [[NSString alloc]initWithFormat:@"%@"
                                       ,[dict objectForKey:@"OK"]];
      
              // IF Status is OK -> 1 so complete the handler
              if ([statusOfApi isEqualToString:@"1"] ) {
      
                  [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                  compilationHandler(TRUE,responseObject,nil);
      
              } else {
      
                  [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
      
                  NSArray *errorMessages = [responseObject objectForKey:@"messages"];
                  NSString *message = [errorMessages objectAtIndex:0];
      
                  [Utilities showAlertViewWithTitle:apiName message:message];
      
                  compilationHandler(FALSE,responseObject,nil);
              }
      
          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
      
              NSString *message = [NSString stringWithFormat:@"%@",[error localizedDescription]];
              NSLog(@"Message is %@", message);
      
              NSString *errorMessage = [NSString stringWithFormat:@"%@",[error localizedDescription]];
              if (!([message rangeOfString:@"The request timed out."].location == NSNotFound)) {
                  [Utilities showAlertViewWithTitle:apiName message:errorMessage];
              }
      
              compilationHandler(FALSE,errorMessage,nil);
          }];
      
          // For internet reachibility check if changes its state
          [self checkInternetReachibility:manager];
      }
      

      **for example when we call the Service **

        // calling service gateway API
      NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       "field",@"value",
                                       nil];
              [self getDataWithObject:dict onAPI:KGet_Preferences  withController:(UIViewController*)controller :^(BOOL success, id response, NSError *error) {
      
                  if( success ) {
                      NSMutableDictionary *data = [[response valueForKey:@"data"] valueForKey:@"preferences"];
                      compilationHandler(success,data,error);
                  } else {
                      compilationHandler(success,nil,error);
                  }
              }];
      

      【讨论】:

      • 也许我遗漏了一些东西,但我看不出它是如何回答这个问题的。问题是如何在 HTTP 请求正文中部分发布参数,部分在 URL 中发布参数。如果我们使用AFHTTPRequestOperationManager POST,默认情况下,AFNetworking会将所有参数放入请求体中。
      • 它没有回答这个问题。在您的方法中,您仅使用 JSON 正文,不使用 URI 参数。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多