ResponseHandler<byte[]> handler, String loReqInfo) throws IOException {
//_reqLogInfo = loReqInfo_;
// if content-type and headers are set, the stream starts
// with "___content_type___\n"
String boundary = "___content_type___\n";
BinResponseHandler brh = (BinResponseHandler)handler;
OutputStream os = brh.getOutputStream();
int n = 0;
int bl = boundary.length();
byte[] buffer = new byte[1024];
while (n < bl) {
byte b = (byte)is.read();
if (b == -1) {
break;
}
buffer[n++] = b;
}
if (new String(buffer, 0, bl).equalsIgnoreCase(boundary)) {
// then retrieve content-type and others headers till reaching \n\n
ByteBuffer bb = ByteBuffer.allocate(1024); // will grows if more space required
bb.clear();
byte prevB = 0, b=0;
while (true) {
prevB = b;
b = (byte) is.read();
if (b == 10 && prevB == 10) { // end of headers
break;
}
bb.put(b);
}
bb.flip();
String[] lines = new String(bb.array(), 0, bb.limit()).split("\n");
bb.clear();
String contentType = null;
Map<String, String> headers = new HashMap<String, String>();
for (String h : lines) {
if (Strings.isNullOrEmpty(h)) {
continue;
}
int pos = h.indexOf(":");
String hn = h.substring(0, pos++);
String hv = h.substring(pos);
if (hn .equalsIgnoreCase("Content-Type")) {
contentType = hv;
} else {
headers.put(hn, hv);
}
}
brh.setContentType(contentType, headers);
} else {
os.write(buffer, 0, bl);
}
while ((n = is.read(buffer)) > -1) {
os.write(buffer, 0, n);
}
brh.end();
}