简体   繁体   English

Android的JSON响应正在被切断

[英]JSON response is getting cut off, Android

I've seen multiple posts about this topic, but none of them seem to be the solution to my problem. 我已经看过很多关于这个主题的帖子,但它们似乎都没有解决我的问题。

The problem is that the JSON response from the server is getting cut off and therefore I'm getting a JSONException when trying to get the response into a JSONArray. 问题是来自服务器的JSON响应正在被切断,因此我在尝试将响应转换为JSONArray时遇到JSONException。

    json = new JSONArray(EntityUtils.toString(response.getEntity()));

Here is the whole code: 这是整个代码:

    private class AsyncFetchForms extends AsyncTask<String, Void, JSONArray> {

    private HttpClient mClient = new DefaultHttpClient();
    private AsyncTaskCompleteListener<JSONArray> listener;
    private String serverUrl;
    private String credentials;

    private ProgressDialog progressDialog;
    private HttpGet httpGet;
    private String response;
    private BasicResponseHandler responseHandler;
    private boolean showDialog;
    private JSONArray json;



    public AsyncFetchForms(String url, String message, AsyncTaskCompleteListener<JSONArray> listener, boolean showDialog)
    {
        serverUrl = Utils.getServerUrl(context) + url;
        credentials = Utils.getUserCredentials(context);
        this.listener = listener;
        this.showDialog = showDialog;

        httpGet = new HttpGet(serverUrl);
        httpGet.setHeader("Authorization", "Basic " + credentials);
        httpGet.setHeader("Accept", "application/json");
        httpGet.setHeader("Accept-Encoding", "gzip");
        httpGet.setHeader("Connection", "keep-alive");

        responseHandler = new BasicResponseHandler();


        if(showDialog)
        {
            progressDialog = new ProgressDialog(context);
            progressDialog.setMessage(message);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);          
            progressDialog.show();
        }
    }


    @Override
    protected JSONArray doInBackground(String... params) {

        try {
            HttpResponse response = mClient.execute(httpGet);


            if (response.getStatusLine().getStatusCode() == 200) {

                json = new JSONArray(EntityUtils.toString(response.getEntity()));

                return json;
            }
        } catch (ClientProtocolException e) {
           e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(JSONArray result) {
        System.out.println(result.toString());

    }
}

Can anyone see the problem? 有谁能看到这个问题?

Logcat can only show about 4000 characters. Logcat只能显示大约4000个字符。 So you will have to implement a recursive function to see the entire log. 因此,您必须实现递归函数才能查看整个日志。 Use below function to see the entire log: 使用以下函数查看整个日志:

public static void longInfo(String str) {
    if (str.length() > 4000) {
        Log.d("", str.substring(0, 4000));
        longInfo(str.substring(4000));
    } else
        Log.d("", str);
}

If you (or your team) implement the server side yourself, first thing I'd check is if the server is returning the correct HTTP response. 如果您(或您的团队)自己实现服务器端,我首先要检查的是服务器是否返回了正确的HTTP响应。 In particular, if you transfer the data by HTTP, you need to have correct Content-Length or otherwise your data will be cut off. 特别是,如果您通过HTTP传输数据,则需要具有正确的Content-Length,否则您的数据将被截断。 Also, Content-Length must be the length of data after any Transfer Encodings are applied, in other words, after the length of the data after being gzipped. 此外, 被gzip压缩之后被施加任何传输编码,换句话说,数据的长度后的Content-Length必须的数据的长度。 Alternatively, use chunked transfer. 或者,使用分块传输。

Second, make sure that your server is generating valid JSON. 其次,确保您的服务器生成有效的JSON。 Maybe you missed a closing parentheses or so. 也许你错过了一个左右的括号。 Maybe you need to parse JSON Object rather JSON Array. 也许你需要解析JSON Object而不是JSON Array。

Also, if you receive exceptions, please always post the the entire traceback. 此外,如果您收到异常,请始终发布整个追溯。

First of all, try to log the EntityUtils.toString(response.getEntity()) response and make sure that it starts with " [ " not " { " ie. 首先,尝试记录EntityUtils.toString(response.getEntity())响应,并确保它以“ [ ”而不是“ { ”ie开头。 it's a jsonArray not jsonObject . 它是一个jsonArray而不是jsonObject

Then try to open the url in your browser ,if avilable, and make sure that there are no encoding issues. 然后尝试在浏览器中打开网址(如果可用),并确保没有编码问题。

Finally, if the problem is still exists please send us the error log output. 最后,如果问题仍然存在,请将错误日志输出发送给我们。

This answer is completely out of the subject but : 这个答案完全超出了主题,但是:

What are you trying do here ? 你在这做什么? Do you know that there are libraries which are doing all this boring job for you ? 你知道有些图书馆正在为你做这些无聊的工作吗?

When I talk about boring job, I'm talking about managing all the background running stuff (like AsyncTask), JSON decoding and HTTP response. 当我谈论无聊的工作时,我正在讨论管理所有后台运行的东西(如AsyncTask),JSON解码和HTTP响应。 I know that it's sometimes a pain in the a** (I've been there) but now I've choose to not worry anymore and use a dedicated library : http://square.github.io/retrofit/ 我知道它有时是a **的痛苦(我去过那里),但现在我选择不再担心并使用专用库: http//square.github.io/retrofit/

This little baby will contact the Webservice of your choice, download the JSON and put it into a custom java class with all the attributes you want to deal with. 这个小宝贝将联系您选择的Web服务,下载JSON并将其放入具有您想要处理的所有属性的自定义Java类中。

If you plug it with something like ORMLite, it can even save your JSON response object into a SQLite DB that you can access in the same way (it "populates" a java class object by setting all the attributes for you). 如果使用ORMLite之类的东西插入它,它甚至可以将您的JSON响应对象保存到您可以以相同方式访问的SQLite DB中(它通过为您设置所有属性来“填充”java类对象)。

Personally I can't imagine myself doing all this stuff by hand anymore, it's just trouble without the benefits =) 就我个人而言,我无法想象自己再用手做所有这些东西,只是麻烦而没有好处=)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM