2012-07-27 47 views
1

我創建了AFHTTPClient的子類,並試圖發送一些JSON參數給服務器。AFNetworking http客戶端不發送JSON參數

但是服務器響應與預期的內容類型

{(
    "text/json", 
    "application/json", 
    "text/javascript" 
)}, got application/xml 

根據AFNetworking FAQ

如果您使用AFHTTPClient,該parameterEncoding屬性設置爲AFJSONParameterEncoding。該HTTP客戶端上帶有參數參數的任何方法現在都會將傳遞的對象編碼爲JSON字符串,並適當地設置HTTP正文和Content-Type標頭。

我已經這樣做了,但服務器似乎無法識別內容頭。有誰知道一個潛在的解決方案?

這裏是方法:

- (void)getCompanyDataWithString:(NSString*)companySearchQuery 
     finish:(LBMarkitAPIRequestCompletionBlock)finishBlock 
{ 
    [self registerHTTPOperationClass:[AFJSONRequestOperation class]]; 
    [self setParameterEncoding:AFJSONParameterEncoding]; 

    NSDictionary *params = [NSDictionary dictionaryWithObject: 
     companySearchQuery forKey:@"input"]; 
    NSMutableURLRequest *searchQueryRequest = [self requestWithMethod:@"GET" 
     path:kMarkitCompanyURL parameters:params]; 

    AFJSONRequestOperation *searchRequestOperation = [AFJSONRequestOperation 
     JSONRequestOperationWithRequest:searchQueryRequest 
     success:^(NSURLRequest *request, NSHTTPURLResponse *response, id json) 
     { 
      NSLog(@"Response: %@", response); 
      NSLog(@"JSON: %@",json); 
      NSMutableArray *results = [NSMutableArray array]; 

      NSError *anError = [[NSError alloc] init]; 
      if ([json objectForKey:@"Message"]) 
      { 
       NSString *message = [json objectForKey:@"Message"]; 
       anError = [[NSError alloc] initWithDomain:message 
                code:100 
               userInfo:nil]; 
      } 

      // Need some error handling code here 
      for (id item in json) 
      { 
       NSString *aName = [item objectForKey:@"Name"]; 
       NSString *aSymbol = [item objectForKey:@"Symbol"]; 
       NSString *anExchange = [item objectForKey:@"Exchange"]; 

       LBCompany *aCompany = [[LBCompany alloc] initWithName:aName 
        Symbol:aSymbol Exchange:anExchange]; 
       [results addObject:aCompany]; 
      } 
      // Need to run the passed in block after JSON 
      // Request Operation succeeds 

      finishBlock(results,anError); 
      } 
     failure:^(NSURLRequest *request, NSHTTPURLResponse *response, 
      NSError *error, id JSON) 
     { 
      NSLog(@"request failed: %@",[error localizedDescription]); 
      NSLog(@"Response: %@",response); 
      NSLog(@"JSON: %@",JSON); 
     }]; 

    [searchRequestOperation start]; 
    NSLog(@"JSON operation started"); 
} 

回答

1

的問題是與URL格式。我沒有注意到一個API實現細節,它使發送查詢參數成爲必需,並且還指定了URI中的JSON輸出。

AFNetworking沒有問題。

+0

嗨,我想我有同樣的問題,但還沒有想出如何解決它。你能告訴我更多關於你在做什麼錯誤的API和你如何修復它。 – filo 2013-06-21 08:49:51

+0

你可以在這裏查看我的解決方案:http://github.com/andrewjl/Aperio/blob/master/Aperio/LBHTTPClient.m – 2013-06-27 19:12:37

+0

謝謝,它幫助了我。 – filo 2013-06-28 17:40:01

相關問題