【问题标题】:Unable to set HTTP body on AFNetworking POST request无法在 AFNetworking POST 请求上设置 HTTP 正文
【发布时间】:2014-08-09 05:48:46
【问题描述】:

我正在尝试使用 AFNetworking 使用 http 正文执行 POST 请求。我用this post's回答

  NSString *urlString = [NSString stringWithFormat:@"my-url"];
  NSString *parameterData = [NSString stringWithFormat:@"request_type=get_story_nids&story_type=%@&story_number=%@", section, count];

  NSURL *url = [NSURL URLWithString:urlString];
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  [request setHTTPMethod:@"POST"];
  [request setHTTPBody:[parameterData dataUsingEncoding:NSUTF8StringEncoding]];
  [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
  [request setValue:@"application/json" forHTTPHeaderField:@"content-type"];
  AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
        op.responseSerializer = [AFJSONResponseSerializer serializer];
        [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id result) {
              completionBlock(nids,nil);  
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            completionBlock(nil, error);
        }];

我在操作 setCompletionBlockWithSuccess 的完成块中放置了断点,它甚至没有命中它。

如果有帮助,做

NSMutableData* result = [[NSURLConnection sendSynchronousRequest:request   returningResponse:&response error:&error] mutableCopy];

有效并为我提供正确的数据。

有什么想法吗?

【问题讨论】:

    标签: ios objective-c post nsurlrequest afnetworking-2


    【解决方案1】:

    给 NSURL 添加断点 *url = [NSURL URLWithString:urlString];如果你得到 url null 然后检查你是否得到正确的 url 然后尝试以下代码

    NSURL *url = [[NSURL alloc] initWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
    NSLog(@"url = %@",url); 
    

    【讨论】:

      【解决方案2】:

      我认为您错过了将操作添加到操作队列的操作。你可以在这里找到一个例子:http://samwize.com/2013/03/02/queue-http-operations-with-afnetworking/

      // Add the operation to a queue
      // It will start once added
      NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
      [operationQueue addOperation:op];
      

      您还可以添加https://github.com/AFNetworking/AFHTTPRequestOperationLogger 来记录 AFNetworking 正在处理的所有操作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-04
        • 2017-03-10
        • 2016-04-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多