当您的服务器理解该请求并想要发送回请求的数据客户端时,您发送200.当您的服务器理解该请求但您不会发回客户端请求的数据时,您发送422.并且&# 39;我的JSON API是如何工作的。保存模型时,我发送200.当模型包含验证错误时,我发送422:
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
不幸的是,当我向Android发送422时,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开发人员?
答案 0 :(得分:0)
如果您收到不成功的响应代码,请阅读错误流。
HttpURLConnection httpConn = (HttpURLConnection)_urlConnection;
InputStream _is;
if (httpConn.getResponseCode() >= 400) {
_is = httpConn.getInputStream();
} else {
/* error from server */
_is = httpConn.getErrorStream();
}
这是错误,关闭为WNF: http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4513568
它为FNFE投掷422响应的事实严重搞砸了。如果您查看HttpURLConnection
的来源,它甚至不会定义422。