Getting an remote servlet image (Please help, very urgent)

Hi,

I have a remote servlet called chartservlet whose url is

http://203.120.153.16/SDS/Chart?Pane1=50;(Study,CBI.N|TRDPRC_1,SMA,200,GREEN,OHLC)&ChartType=HISTORICAL&FillColor=PINK&GridColor=YELLOW&TextColor=YELLOW&DataRepresentation=Charts

this servlet creates an chart image dynamically and displays to the requester(client).

Now in a local servlet that is running in tomcat(locally in my system) i am trying to connect to the remote servlet through HTTP url connection to retrive the resulting image into an byte array. the code snippet is as below:

public byte[] getByteContents(URL url) throws Exception

{

int responseCode;

HttpURLConnection connection;

InputStream input;

BufferedReader dataInput;

connection = (HttpURLConnection)url.openConnection();

responseCode = connection.getResponseCode();

if (responseCode != HttpURLConnection.HTTP_OK) {

throw new Exception("HTTP response code: " +

String.valueOf(responseCode));

}

byte [] b=null;

try {

input = connection.getInputStream();

int avail=input.available();

b=new byte[avail];

input.read(b);

input.close();

} catch (Exception ex) {

ex.printStackTrace(System.err);

return null;

}

return b;

}

}

where the url passed to the getByteContents() method is the same as the above one i.e

http://203.120.153.16/SDS/Chart?Pane1=50;(Study,CBI.N|TRDPRC_1,SMA,200,GREEN,OHLC)&ChartType=HISTORICAL&FillColor=PINK&GridColor=YELLOW&TextColor=YELLOW&DataRepresentation=Charts

then i am writing the resulting byte array into the output stream

private static final String CONTENT_TYPE = "image/png";

ServletOutputStream out=response.getOutputStream();

byte[] imgBytes = getByteContents(url);

out.write(imgBytes);

But the image is not getting displayed, but when i used to run the same url through my browser the image gets displayed properly.

Can somebody please help me to resolve this problem. It is very urgent, if anybody give a small hint also it will be very greatfull for me.

Hoping to get good responses.

Thanks & Regards

-Sandeep

[2285 byte] By [km-sandeepa] at [2007-10-2 17:58:01]
# 1

It looks like there's a problem in your read code:

int avail=input.available();

b=new byte[avail];

input.read(b);

Because all the data won't necessarily be received at once, the avail

won't be reliable.

I'd use something like this instead:

int avail = connection.getContentLength(); // if you trust content-length

if (avail >= 0) {

b = new byte[avail];

input.read(b);

}

else {

// read to end of file

ArrayList al = new ArrayList();

int bb;

while ((bb = input.read()) != -1)

al.add(new Byte((byte) bb));

b = new byte[al.size()];

for (int i = 0; i < al.size(); i++)

b[i] = ((Byte) al.get(i)).byteValue();

}

There are better ways to do the buffering in the case that content-length = -1....

Gerald.Hanwecka at 2007-7-13 19:16:52 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...