Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
811 views
in Technique[技术] by (71.8m points)

android - What is the reason of this error java.io.IOException: Content-Length and stream length disagree

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 != -1L && contentLength != bytes.size.toLong()) {
  throw IOException(
      "Content-Length ($contentLength) and stream length (${bytes.size}) disagree")
}

but how to fix that ?

edit:

enter image description here

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

    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

BNK's screenshot


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...