这是什么错误java.io.IOException异常的原因:内容长度和流长度不同意长度、不同意、异常、错误

2023-09-05 03:47:08 作者:怼

我收到此错误

  java.io.IOException异常:内容长度和流长度不同意
 

在这条线的code 返回response.body()个字节();

这是满code

编辑:在错误的一些谷歌的原因是从 okhttp LIB

 如果(CONTENTLENGTH = -1放大器;!&安培;!CONTENTLENGTH = bytes.length){
      抛出新的IOException异常(内容长度和流长度不同意);
    }
 
Java基础篇 异常详解

但如何解决这个问题?

编辑:

这是满code:

 公共类OkHttpHandler扩展的AsyncTask<虚空,虚空,byte []的> {

    私人最终字符串Fetch_URL =htt​​p://justedhak.comlu.com/get-data.php;
    ArrayList的<列表项>列表项;
    INT resulta;

    OkHttpClient的HttpClient =新OkHttpClient();

    字符串myJSON;
    JSONArray人民= NULL;
    的InputStream的InputStream = NULL;

    @覆盖
    受保护的byte [] doInBackground(虚空...... PARAMS){
        Log.d(E,DDDDDDDDDD);
        Log.d(E,Fetch_URL);

        Request.Builder建设者=新Request.Builder();
        builder.url(Fetch_URL);

        请求请求= builder.build();

        字符串结果= NULL;
        尝试 {

            响应响应= httpClient.newCall(要求).execute();
          // INT状态code = response.getStatusLine()的getStatus code();

              INT状态code = 200;

           // HttpEntity实体= response.body()的字节流()。
            如果(状态code == 200){
                byte []的缓冲区=新的字节[8192];
                INT读取动作;
                ByteArrayOutputStream输出=新ByteArrayOutputStream();
                而((读取动作= inputStream.read(缓冲液))!=  -  1){
                    output.write(缓冲液,0,读取动作);
            //为InputStream = response.body()的字节流()。

                // JSON是UTF-8在默认情况下
             //的BufferedReader读卡器=新的BufferedReader(新的InputStreamReader(InputStream中,UTF-8),8);
            / * StringBuilder的SB =新的StringBuilder();

                串线= NULL;
                而((行= reader.readLine())!= NULL)
                {
                    sb.append(行+\ N);
                }
                结果= sb.toString(); * /
                resulta = 1; //成功
                Log.d(E,回应);
                返回response.body()个字节()。

            }
            其他
            {
                resulta = 0; //失败

            }
        }赶上(例外五){

            Log.d(E,r2r2错误);

            e.printStackTrace(); }
        最后 {
            尝试{如果(的InputStream!= NULL)inputStream.close();}赶上(例外挤){}
        }
        返回null;
    }

    保护无效onPostExecute(字符串结果){
        如果(resulta == 1){
            myJSON =结果;
            showList();
        }
        其他{
            Log.e(D,zzzzzzzz);

        }
    }

    保护无效showList(){
        尝试 {
            Log.e(D,jjjjjjjjjj);

            JSONObject的jsonObj =新的JSONObject(myJSON);
            人民= jsonObj.getJSONArray(结果);
            列表项=新的ArrayList<列表项>();
            的for(int i = 0; I< peoples.length();我++){
                JSONObject的C = peoples.getJSONObject(我);
                字符串ID = c.getString(ID);
                字符串URL = c.getString(路径);
                Listitem.add(新列表项(ID,网址));
                Log.e(D,PPPPP);
            }

         // GridViewAdapter适配器=新GridViewAdapter(这一点,R.layout.grid_item_layout,列表项);
            // gridView.setAdapter(gridAdapter);
           // adapter.notifyDataSetChanged();

            // list.setAdapter(适配器);

        }赶上(JSONException E){
            e.printStackTrace();
        }

    }
}
 

解决方案

这抛出异常,因为你叫的InputStream的InputStream = response.body()的字节流(); 然后叫 response.body()个字节(); 再次

您可以使用从的InputStream 返回result.getBytes返回字节数组(); 来代替,如果这是你想回到什么。

在的InputStream 的到的字节的参考以下内容:

 公共字节[] getBytesFromInputStream(InputStream中的InputStream)抛出IOException异常{
        尝试 {
            byte []的缓冲区=新的字节[8192];
            INT读取动作;
            ByteArrayOutputStream输出=新ByteArrayOutputStream();
            而((读取动作= inputStream.read(缓冲液))!=  -  1){
                output.write(缓冲液,0,读取动作);
            }
            返回output.toByteArray();
        }赶上(OutOfMemoryError异常错误){
            返回null;
        }
    }
 

更新:的

如果您在调试 ResponseBody.class ,你将看到下面的截图:

I am getting this error

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

on this line of code return response.body().bytes();

this is full code

edit: after some google the reason of the error is from okhttp lib

 if (contentLength != -1 && contentLength != bytes.length) {
      throw new IOException("Content-Length and stream length disagree");
    }

but how to fix that ?

edit:

this is full code:

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();
        }

    }
}

解决方案

That Exception thrown because you have called InputStream inputStream = response.body().byteStream(); then called response.body().bytes(); again.

You can use return bytes array from the inputStream or return result.getBytes(); instead if that is what you want to return.

From inputStream to bytes refer to the following:

    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;
        }
    }

UPDATE:

If you debug at ResponseBody.class, you will see as the following screenshot: