Android - 使用返回 nothing/empty 的 InputStream 获取数据

Android - Get Data using InputStream returning nothing/empty

我正在解析 JSON 的数据,它从下面这样开始...

[
   {"title":"dummy", "content":"ajsfhk"},
   {"title":"dummy", "content":"ajsfhk"},
   {"title":"dummy", "content":"ajsfhk"},
]

下面是我的 android 异步任务 class。但它显示“NegativeArraySizeException

class RetrieveFeedTask extends AsyncTask<Object, Void, String> {

    @Override
    protected String doInBackground(Object... arg0) {
        int responseCode = -1;
        try {
            URL retailerUrl = new URL("https://clients.appatlantis.com/soldy/wp-json/wp/v2/soldy-clients?_embed");
            HttpsURLConnection connection = (HttpsURLConnection) retailerUrl.openConnection();
            connection.connect();

            responseCode = connection.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                Reader reader = new InputStreamReader(inputStream);
                int contentLength = connection.getContentLength();
                char[] charArray = new char[contentLength];
                reader.read(charArray);
                String responseData = new String(charArray);
                Log.e(TAG, "Parse Data "+responseData);
            } else {
                Log.e(TAG, "Parse Data Failed");
            }

        } catch (MalformedURLException e) {
            Log.e(TAG, "URL Exeption: ", e);
        } catch (IOException e) {
            Log.e(TAG, "IO URL Exeption: ", e);
        } catch (Exception e) {
            Log.e(TAG, "Exeption Caught: ", e);
        }

        return "Response Code "+responseCode;
    }
}

这是异常跟踪

2020-04-10 15:12:31.322 27385-27449/com.appatlantis.soldy E/MainActivity: Exeption Caught: 
    java.lang.NegativeArraySizeException: -1
        at com.appatlantis.soldy.MainActivity$RetrieveFeedTask.doInBackground(MainActivity.java:149)
        at com.appatlantis.soldy.MainActivity$RetrieveFeedTask.doInBackground(MainActivity.java:132)
        at android.os.AsyncTask.call(AsyncTask.java:333)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:245)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)

我不太了解JSON。

contentLength-1。注意错误:

    java.lang.NegativeArraySizeException: -1
        at com.appatlantis.soldy.MainActivity$RetrieveFeedTask.doInBackground(MainActivity.java:149)

这告诉你你试图在第 149 行初始化一个大小为 -1 的数组,我假设基于崩溃是

char[] charArray = new char[contentLength];

根据 getContentLength() 的文档,这意味着内容长度未知。您应该考虑直接从 InputStream 解析 JSON - 它会为您省去尝试自己执行此操作的麻烦。