當您的服務器瞭解請求並希望發回請求的數據客戶端時,您會發送一個200.當您的服務器瞭解請求但您不會發回客戶端請求的數據時,您發送一個422.而這正是我的JSON API的工作原理。當一個模型保存,我送200。當模型中包含驗證錯誤,我送422:使用JSON API的狀態代碼
respond_to do |format|
if @user.persisted?
format.json do
render json: { id: @user.id }, status: 200
end
else
format.json do
render json: { error: @user.errors.full_messages }, status: 422
end
end
end
不幸的是,當我發送422至Android,HttpURLConnection類拋出試圖訪問輸入流時異常:
W/System.err: java.io.FileNotFoundException: http://10.0.2.2:3001/users/auth/facebook/callback.json
現在,如果我在我的JSON API中將422更改爲200,則不會引發異常,並且我能夠解析數據。
url = new URL(OMNI_AUTH_CALLBACK);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params[0]));
writer.flush();
writer.close();
os.close();
int status = urlConnection.getResponseCode();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while(data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
但是,響應不應該是200,因爲存在保存數據的問題。什麼是Android開發者要做的?
???所以422你得到一個錯誤,200你沒有得到一個錯誤,你說這個迴應不應該是200,對吧?那麼你需要什麼,422或200,錯誤或沒有錯誤? – user7568042
@ user7568042我已經在我的問題中解釋了它:當模型沒有保存時,我想發回一個422.但是,當我發送422到Android時,它引發了一個異常,並且不允許我處理錯誤消息JSON迴應422狀態碼。 – Donato