12

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

    }
}
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Moudiz
  • 7,211
  • 22
  • 78
  • 156
  • @BNK I still didnt check it I am at work hopefully at night ill test it. thank you very much – Moudiz Oct 13 '15 at 11:40
  • @BNK I got the following error . check edit image – Moudiz Oct 13 '15 at 20:39
  • Just need to add try-catch block. – BNK Oct 13 '15 at 21:03
  • In your edited code, where was `inputStream` initialized? – BNK Oct 13 '15 at 21:52
  • @BNK after the class declaration. ill add the full code check plz edit – Moudiz Oct 14 '15 at 08:43
  • So, what was the error you got? IOException? – BNK Oct 14 '15 at 09:31
  • @BNK check this plz http://stackoverflow.com/questions/33121780/code-not-continueing-to-onpostexecute – Moudiz Oct 14 '15 at 09:39
  • We are at different time-zones, so sometimes I am late for your issue :) – BNK Oct 14 '15 at 12:19
  • @BNK its ok I solve it now thanks to you.. now I am having different issue ill post a questions now .. by the way where do you live? in the states ? – Moudiz Oct 14 '15 at 12:26
  • I live in Vietnam, at night now, and I'm online on mobile (lol) – BNK Oct 14 '15 at 12:31
  • 1
    oh nice to meet you . I live in lebanon have you heard about it before ? now its 3:31 pm here .. btw this is the question that I have posted now http://stackoverflow.com/questions/33125404/object-in-object-cannot-be-applied-while-creating-adapter-image – Moudiz Oct 14 '15 at 12:33
  • Nice to meet you too. I know that you are starting to learn Android, so if you have freetime, you can refer to some of my answers I have posted in StackOverflow with working sample codes :) – BNK Oct 14 '15 at 13:24
  • @bnk you really helped me in many answers I have posted. however your answers doesnt always refer to my problems that I face . but if anytime you have an answer for my problem that you already answered please send me the link – Moudiz Oct 14 '15 at 21:34
  • are you using new relic integration? I think this is related – bryant1410 Oct 23 '15 at 12:01
  • @bryant1410 can you please explain more what do you mean by that ? – Moudiz Oct 23 '15 at 12:33
  • 2
    @Moudiz New Relic SDK had known issues with Retrofit 2 (https://discuss.newrelic.com/t/problem-with-responsebuilderextension-retrofit-2-0/27081). They supposedly fixed it, but since I re-enable it with the new version, it started giving this error when looking at error body string (didn't research more, but I strongly think it's because of this). – bryant1410 Oct 23 '15 at 13:30

1 Answers1

18

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

BNK
  • 23,994
  • 8
  • 77
  • 87