-1

when i tryin to make thme method .toByteArray(); always fall in a exception, but the log doesn´t show, what can be the problem:

protected byte[] GetResponseBytes(HttpURLConnection conn)
{
    byte[] data2 = null;
    try
    {
        int nRead;
        byte[] data = new byte[16384];
        InputStream is = conn.getInputStream();
        ByteArrayOutputStream buff = new ByteArrayOutputStream();

        while ((nRead = is.read(data, 0, data.length)) != -1)
            buff.write(data, 0, nRead);

        buff.flush();
        buff.close();
        is.close();
        data2 = buff.toByteArray();
        return data2;

    }
    catch (Exception ex)
    {
        Log.d(" ERROR ", "[ data loader - post response bytes ] "+ex.getMessage());
        return data2;
    }
}

and i call the method like this:

byte[] data = GetResponseBytes(conn);
            element = parser.parseFrom(data);

the parser is a protocolBuffer and make an excepcion

2 Answers2

0

You have closed the buffer "buff" at the line: buff.close(); then you are accessing it. Close it after accessing it - not before :-)

Kofi
  • 524
  • 5
  • 7
  • What is the exception you are getting? Try putting a break point on the line where the Log call is rather than relying on the log itself. – Kofi Jan 13 '16 at 08:03
  • com.google.protobuf.InvalidProtocolBufferException: Protocol message tag had invalid wire type. – Cristian Franco Alba Jan 13 '16 at 14:53
  • OK, look at the accepted answer to a similar problem [here](http://stackoverflow.com/questions/4870528/how-should-i-record-httpservletrequests-that-are-sent-to-dopost-in-an-https/4963983#4963983). I think for your particular problem you need to read/write your byte array using a CodedOutputStream as described in the link. – Kofi Jan 14 '16 at 08:36
0

data2 = buff.toByteArray(); buff.flush(); buff.close();`