簡體   English   中英

無法在AFNetworking POST請求上設置HTTP正文

[英]Unable to set HTTP body on AFNetworking POST request

我正在嘗試使用AFNetworking與http正文進行POST請求。 我用這個帖子的答案

  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);
        }];

我在op setCompletionBlockWithSuccess的完成塊中放置了斷點,它甚至沒有擊中它。

如果有幫助,那就做

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

可以給我正確的數據。

有任何想法嗎?

將斷點添加到NSURL * url = [NSURL URLWithString:urlString]; 並檢查是否獲得正確的URL(如果您獲得的URL為空),然后嘗試以下代碼

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

我認為您錯過了將您的操作添加到操作隊列的操作。 您可以在此處找到示例: 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正在處理的所有操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM