2013-07-15 87 views
6

我收到JSON字符串中不良區AFNetworking預期的內容類型錯誤

NSURL *url = [[NSURL alloc] initWithString:@"http://www.vinipost.com/Services/Update/UpdateService.asmx/GetPropSubType?"]; 
     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; 
     [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]]; 

     AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 

      NSLog(@"%@", JSON); 
     } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { 
      NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo); 
     }]; 
     [operation start]; 

輸出:

Request Failed with Error: Error Domain=AFNetworkingErrorDomain Code=-1016 "Expected content type {(
    "text/json", 
    "text/javascript", 
    "application/json", 
    "text/html" 
)}, got text/plain" UserInfo=0x71521a0 {NSLocalizedRecoverySuggestion=[{"PropTypId":1,"PropCatId":1,"PropTyp":"Flat/ Condo"}.......** 

回答

5

的錯誤是明顯的: Web服務返回一個錯誤的內容類型。 內容類型應該是其中之一:

「文/ JSON」, 「文/ JavaScript的」, 「應用/ JSON」, 「text/html的」

但返回

text/plain的

而且,如果你看看http響應,它會在裏面返回HTML TAGS,所以AFNetworking不能解析。

如果此頁:

http://www.vinipost.com/Services/Update/UpdateService.asmx/GetPropSubType? 

是你的控制之下,糾正行爲刪除HTML標籤和更改內容類型

+0

@ LombaX-行,所以如何處理它 –

+0

將UpdateService.asmx網頁的代碼更改爲使用文本/純文本內容類型返回正確的JSON響應。我不能幫你用ASP – LombaX

+0

@ lombaX-感謝,錯誤已經從服務器端修正.. –

4

在AFNetworking,你必須創建的NSURLRequest與AFHTTPClient的幫助(所以首先你必須創建AFHTTPClient和必須設置此對象的某些屬性)像下面

AFHTTPClient *httpClient = [[httpClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://www.vinipost.com/"]];

[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]]; 
    [httpClient setDefaultHeader:@"Accept" value:@"application/json"]; 
    httpClient.parameterEncoding = AFJSONParameterEncoding; 

現在如果依賴GET/POST或任何其他類型的請求,你需要設置參數,我認爲這是POST請求,所以設置參數字典,並設置所有必需的鍵值對properly.if沒有,你可以傳遞參數所需的參數作爲nil

NSURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"Services/Update/UpdateService.asmx/GetPropSubType?" parameters:params]; 
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request 
            success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) 
            { 
             NSLog(@"%@",JSON); 

            } 
            failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) 
            { 
             NSLog(@"Error MSG = %@",error); 
            }]; 

[operation start]; 

希望這會爲你工作:)

10

你需要操作前加入這一行

[AFJSONRequestOperation addAcceptableContentTypes: 
          [NSSet setWithObject:@"text/plain"]];
+0

-the問題是從服務器端的期望答案解釋 –

+1

這也是一個正確的答案。指出'問題來自服務器端'是不正確的 - 問題被指定爲發生的錯誤消息,因此可能已在服務器端或客戶端修復以提供工作解決方案。 –

+0

@ CarlosP-我首先嚐試了斯坦尼斯拉夫,但得到同樣的問題。無法修復它在客戶端。 –

相關問題