这个错误的原因是什么?java.io.IOException: Content-Length and stream length disagree。

12

我遇到了这个错误

   java.io.IOException: Content-Length and stream length disagree

在这行代码上 return response.body().bytes();

这是完整代码。

编辑:经过一些谷歌搜索,错误的原因来自于okhttp库

if (contentLength != -1L && contentLength != bytes.size.toLong()) {
  throw IOException(
      "Content-Length ($contentLength) and stream length (${bytes.size}) disagree")
}

但如何解决这个问题?

编辑:

在此输入图片描述

这是完整的代码:

public class OkHttpHandler extends AsyncTask<Void, Void, byte[]> {

    private final String Fetch_URL = "http://justedhak.comlu.com/get-data.php";
    ArrayList<Listitem> Listitem;
    int resulta;

    OkHttpClient httpClient = new OkHttpClient();

    String myJSON;
    JSONArray peoples = null;
    InputStream inputStream = null;

    @Override
    protected byte[] doInBackground(Void... params) {
        Log.d("e", "dddddddddd");
        Log.d("e", Fetch_URL);

        Request.Builder builder = new Request.Builder();
        builder.url(Fetch_URL);

        Request request = builder.build();

        String result = null;
        try {

            Response response = httpClient.newCall(request).execute();
          //  int statusCode = response.getStatusLine().getStatusCode();

              int statusCode =200;

           // HttpEntity entity = response.body().byteStream();
            if (statusCode == 200) {
                byte[] buffer = new byte[8192];
                int bytesRead;
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    output.write(buffer, 0, bytesRead);
            //    inputStream = response.body().byteStream();

                // json is UTF-8 by default
             //   BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
            /*    StringBuilder sb = new StringBuilder();

                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                result = sb.toString();*/
                resulta = 1; //"Success
                Log.d("e", "response.");
                return response.body().bytes();

            }
            else
            {
                resulta = 0; //"Failed

            }
        } catch (Exception e) {

            Log.d("e", "r2r2 error");

            e.printStackTrace();        }
        finally {
            try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
        }
        return null;
    }

    protected void onPostExecute(String result){
        if( resulta ==1){
            myJSON=result;
            showList();
        }
        else{
            Log.e("d","zzzzzzzz");

        }
    }

    protected void showList(){
        try {
            Log.e("d","jjjjjjjjjj");

            JSONObject jsonObj = new JSONObject(myJSON);
            peoples = jsonObj.getJSONArray("result");
            Listitem = new ArrayList<Listitem>();
            for(int i=0;i<peoples.length();i++){
                JSONObject c = peoples.getJSONObject(i);
                String id = c.getString("id");
                String url = c.getString("path");
                Listitem.add(new Listitem(id,url));
                Log.e("d","ppppp");
            }

         //   GridViewAdapter adapter = new GridViewAdapter(this, R.layout.grid_item_layout, Listitem);
            //   gridView.setAdapter(gridAdapter);
           // adapter.notifyDataSetChanged();

            //  list.setAdapter(adapter);

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}

@BNK 我还没有检查它,我现在正在工作,希望晚上能测试一下。非常感谢你。 - Moudiz
只需要添加try-catch块即可。 - BNK
在您编辑的代码中,inputStream 在哪里被初始化了? - BNK
1
哦,很高兴见到你。我住在黎巴嫩,你听说过吗?现在这里是下午3:31。顺便说一下,这是我刚刚发布的问题:https://dev59.com/WJDea4cB1Zd3GeqPWxVg - Moudiz
2
@Moudiz New Relic SDK与Retrofit 2存在已知问题(https://discuss.newrelic.com/t/problem-with-responsebuilderextension-retrofit-2-0/27081)。他们据说已经修复了这个问题,但是自从我重新启用了新版本后,在查看错误消息体字符串时它开始出现这个错误(没有进行更多的研究,但我强烈认为是因为这个问题)。 - bryant1410
显示剩余11条评论
1个回答

18

抛出异常的原因是您调用了 InputStream inputStream = response.body().byteStream(); 然后又再次调用了 response.body().bytes();

如果您想要返回结果,可以使用从 inputStream 中获取的字节数组或者使用 return result.getBytes();

inputStreambytes 的转换请参考以下内容:

    public byte[] getBytesFromInputStream(InputStream inputStream) throws IOException {
        try {            
            byte[] buffer = new byte[8192];
            int bytesRead;
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }
            return output.toByteArray();
        } catch (OutOfMemoryError error) {
            return null;
        }
    }

更新:

如果你在ResponseBody.class进行调试,你会看到如下截图:

BNK's screenshot


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接