iOS 出現問題:POST 網路請求狀態 code:500 的解決方法
前言:
在 iOS 10 中,我用 [NSURLSession uploadTaskWithRequest:request fromData:jsondata completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error){}]; 進行 POST 請求時出現了 500 錯誤。
500 代表伺服器遇到未預料的狀況,導致無法完成請求,通常是伺服器程式碼出錯。雖然這是伺服器端的問題,但我認為伺服器在解析請求資料時也可能因此回傳 500,於是決定從客戶端著手排查。
列印回應的 response 得到:
:<NSHTTPURLResponse: 0x17003a900> { URL: 你的url地址 } { status code: 500, headers { "Cache-Control" = private "Content-Length" = 3306; "Content-Type" = "text/html; charset=utf-8"; Date = "Sun, 09 Oct 2016 07:45:13 GMT"; Server = "Microsoft-IIS/7.5"; "X-AspNet-Version" = "4.0.30319"; "X-Powered-By" = "ASP.NET"; } }
可以看到回傳類型不是 json,而是 text/html。而 POST 請求需要設定請求頭的資料類型,我出錯的請求是這樣設定的:
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
這個設定是從提交圖片的請求方法複製過來的,也就是說 application/x-www-form-urlencoded 是提交圖片的類型。而我這次請求提交的是 json 字串的 NSData,因此 Content-Type 應該設為 application/json 才對。
修改方式如下:
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
修改後的回應可與上面對照:
<NSHTTPURLResponse: 0x17403fe60> { URL: 你的url地址 } { status code: 200, headers { "Cache-Control" = private; "Content-Length" = 75; "Content-Type" = "application/json; charset=utf-8"; Date = "Sun, 09 Oct 2016 07:56:16 GMT"; Server = "Microsoft-IIS/7.5"; "X-AspNet-Version" = "4.0.30319"; "X-AspNetMvc-Version" = "4.0"; "X-Powered-By" = "ASP.NET"; } }
此時 status code 已變為 200,500 錯誤獲得解決。當然,這個錯誤也可能是後端處理資料出錯,或後端回傳的資料類型與前端期望的類型衝突所致,仍需具體問題具體分析。以上就是本文的全部內容,希望對大家有所幫助。