2017-03-02 39 views
0

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

+0

???所以422你得到一个错误,200你没有得到一个错误,你说这个回应不应该是200,对吧?那么你需要什么,422或200,错误或没有错误? – user7568042

+0

@ user7568042我已经在我的问题中解释了它:当模型没有保存时​​,我想发回一个422.但是,当我发送422到Android时,它引发了一个异常,并且不允许我处理错误消息JSON回应422状态码。 – Donato

回答

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.

+0

是的,该文件没有找到错误,把我从大时间。我不知道它在说什么。 – Donato

+0

我很好奇,看看它为其他众所周知的4xx代码抛出了什么...... –