当您的服务器了解请求并希望发回请求的数据客户端时,您会发送一个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