Android的,问题解析JSON由422响应返回 [英] Android, Problems parsing json returned by a 422 response

查看:906
本文介绍了Android的,问题解析JSON由422响应返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Web服务器与422无法处理的实体错误响应,并呈现与错误列表JSON响应
例如。

  {名:已拍摄]}

出于某种原因,虽然我的Andr​​oid应用程序拒绝承认有任何JSON在任何的响应。

 的Htt presponse响应= Htt的prequest.httpPostJSONObject(这一点,Urls.getUrlForAccountTeams(本),tm.getJsonObject(),令牌);
。INT code = response.getStatusLine()的getStatus code();
如果(code == 422){
    串responseJson = EntityUtils.toString(response.getEntity());
    JSONObject的responseEntity =新的JSONObject(responseJson);
    Log.i(TAG,创建的帐户错误+ responseEntity.toString());
}

从上面的日志消息以下输出

  I / ServiceRefreshData(780):服务器响应422
I / ServiceRefreshData(780):创建的帐户错误{}

如果我用卷曲张贴完全相同的消息作为我的Andr​​oid应用程序来模拟这种发送我得到的JSON如上图 {名:已拍摄]} 而这正是我期待在​​我的Andr​​oid应用程序,看看

如何获得JSON的任何想法。我在与解析全成JSON响应任何问题。

要发送JSON的请求使用org.apache.http.Htt presponse该职位要求的结果。

 公共静态的Htt presponse httpPostJSONObject(上下文的背景下,字符串URL,JSONObject的数据,字符串标记)抛出ClientProtocolException,IOException异常{
        HttpClient的HttpClient的=新DefaultHttpClient();
        HttpPost httppost =新HttpPost(URL);
        setHeaders(httppost,令牌);
        StringEntity本身=新StringEntity(data.toString());        httppost.setEntity(SE);
        返回httpclient.execute(httppost);
    }

更新为了进一步澄清我setHeaders方法看起来像这样

 私有静态无效setHeaders(HTT prequestBase HTTPGET,字符串标记){
    httpget.addHeader(接受,应用/ JSON);
    httpget.addHeader(内容类型,应用/ JSON的;字符集= UTF-8);
    如果(令牌!= NULL){
        httpget.addHeader(授权,令牌令牌=+令牌);
    }
}

有关完整性在我的网络服务器(Rails的3.2.12),它生产这种JSON的$​​ C $ c是

 的respond_to做|格式|
  如果@ team.save
    format.html {redirect_to的@team,通知:团队已成功创建。 }
    format.json {渲染JSON:@team,状态:创建,位置:[:API,@team]}
  其他
    format.html {渲染动作:新}
    format.json {渲染JSON:@ team.errors,状态:unprocessable_entity}
  结束
结束

更新有更多的调试信息按评论
改变我的日志消息,所以我的方法现在发送数据的结果看起来像这样

  {尝试
            HTT presponse响应= HTT prequest.httpPostJSONObject(这一点,Urls.getUrlForAccountTeams(本),tm.getJsonObject(),令牌);
            。INT code = response.getStatusLine()的getStatus code();
            Log.i(TAG服务器响应+ code);
            如果(code == 422){
                串responseJson = EntityUtils.toString(response.getEntity());
                JSONObject的responseEntity =新的JSONObject(responseJson);
                Log.i(TAG,创建帐户的错误响应实体+ responseEntity.toString());
                Log.i(TAG,创建的帐户错误响应+ response.toString());
                Log.i(TAG,创建的帐户错误ResponseJson+ responseJson.toString());
            }
        }赶上(ClientProtocolException E){
            // TODO自动生成catch块
            e.printStackTrace();
        }赶上(IOException异常五){
            // TODO自动生成catch块
            e.printStackTrace();
        }赶上(JSONException E){
            // TODO自动生成catch块
            e.printStackTrace();
        }

和产生

  I / ServiceRefreshData(814):服务器响应422
I / ServiceRefreshData(814):创建帐户的错误响应实体{}
I / ServiceRefreshData(814):创建帐户的错误响应org.apache.http.message.BasicHtt$p$psponse@44ec4978
I / ServiceRefreshData(814):创建的帐户错误ResponseJson {}


解决方案

重新启动我的电脑问题只是走了之后。我真的这个整个事件感到不解。我确信我的code是正确的,日志的输出被证明事实并非如此。我只能把这归因于某种高深莫测的缓存问题。

非常感谢那些帮助。

My web server responds with a 422 unprocessable entity error and renders a json response with a list of the errors e.g.

{"name":["has already been taken"]}

For some reason though My android app refuses to acknowledge that there is any json whatsoever in the response.

HttpResponse response = HttpRequest.httpPostJSONObject(this, Urls.getUrlForAccountTeams(this), tm.getJsonObject(), token);
int code = response.getStatusLine().getStatusCode();
if (code == 422){
    String responseJson = EntityUtils.toString(response.getEntity());
    JSONObject responseEntity = new JSONObject(responseJson);
    Log.i(TAG, "Created account errors " + responseEntity.toString());
}

The following output from the above Log message is

I/ServiceRefreshData(  780): Server response 422
I/ServiceRefreshData(  780): Created account errors {}

If I use curl to emulate this by posting exactly the same message as my android app is sending I get the json as shown above {"name":["has already been taken"]} and this is exactly what I am expecting to see in my android app

Any ideas on how to get the json. I'm having no issues with parsing successfull json responses

The request to send the json uses org.apache.http.HttpResponse for the result of the post request

    public static HttpResponse httpPostJSONObject(Context context, String url, JSONObject data, String token) throws ClientProtocolException, IOException{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        setHeaders(httppost, token);
        StringEntity se = new StringEntity(data.toString());

        httppost.setEntity(se);
        return httpclient.execute(httppost);
    }

UPDATE For further clarity my setHeaders method looks like this

private static void setHeaders(HttpRequestBase httpget, String token) {
    httpget.addHeader("Accept", "application/json");
    httpget.addHeader("Content-Type", "application/json; charset=UTF-8");
    if(token != null){
        httpget.addHeader("Authorization", "Token token="+token);
    }
}

For completeness the code on my webserver (Rails 3.2.12) that is producing this json is

respond_to do |format|
  if @team.save
    format.html { redirect_to @team, notice: 'Team was successfully created.' }
    format.json { render json: @team, status: :created, location: [:api, @team] }
  else
    format.html { render action: "new" }
    format.json { render json: @team.errors, status: :unprocessable_entity }
  end
end

UPDATE with more debugging info as per comment Result of changing my log messages so my method for sending the data now looks like this

        try {
            HttpResponse response = HttpRequest.httpPostJSONObject(this, Urls.getUrlForAccountTeams(this), tm.getJsonObject(), token);
            int code = response.getStatusLine().getStatusCode();
            Log.i(TAG, "Server response " + code);
            if (code == 422){
                String responseJson = EntityUtils.toString(response.getEntity());
                JSONObject responseEntity = new JSONObject(responseJson);
                Log.i(TAG, "Created account errors Response Entity " + responseEntity.toString());
                Log.i(TAG, "Created account errors Response " + response.toString());
                Log.i(TAG, "Created account errors ResponseJson " + responseJson.toString());
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

And produces

I/ServiceRefreshData(  814): Server response 422
I/ServiceRefreshData(  814): Created account errors Response Entity {}
I/ServiceRefreshData(  814): Created account errors Response org.apache.http.message.BasicHttpResponse@44ec4978
I/ServiceRefreshData(  814): Created account errors ResponseJson {}

解决方案

After re-booting my PC The problem just went away. I am really puzzled by this whole episode. I was convinced my code was right and the log output was proving it wasn't. I can only put this down to some totally unfathomable caching issue.

A big thank you to those that helped.

这篇关于Android的,问题解析JSON由422响应返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆