views:

22

answers:

2

Hello

Can anyone tell me if they know how to use the Google Chart API to store the image returned in the file system rather than be included in a webpage?

My situation is that I'd like a Java servlet or a listener to run at regular intervals on an Apache Tomcat server to make HTTP GET / POST requests to the Google Chart API and store the resulting images in the file system or application database. Later on the images would be placed in HTML pages.

Presumably I'm looking at something like this:

String result = null;
URL url = new URL(urlStr);
URLConnection conn = url.openConnection ();

BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = rd.readLine()) != null)
{
    sb.append(line);
}
rd.close();
result = sb.toString();

Where result is the image which can be written to file or database? But where some output may have to be stripped out.

Any advice is welcome.

Mr Morgan.

A: 

Write a program that opens an HTTP connection to a Google Chart API URL, such as http://chart.apis.google.com/chart?cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World

Read the response stream and write it to a FileOutputStream

If you need more specific help than this, please write a comment or update the question with more specific questions :-)

EDIT:

Since it's binary data and not textual data, do not use Readers - instead work directly with the InputStream. Read bytes into a temp buffer and write them to a FileOutputStream.

ob1
Question has been revised.
Mr Morgan
Thanks. Will try this later. The alternative is to request images whenver the page is loaded which may mean frequent duplicate requests.
Mr Morgan
There's going to be a request for an image from the client anyway - either to your server or directly to Google's.You can perhaps assume that google handles the traffic and caching issues better than you and not worry about it ...
ob1
Perhaps. But I'd like to eliminate waste of repeated requests.
Mr Morgan
@ob1: It works quite nicely and I can specify file names which is helpful. Thanks for help.
Mr Morgan
A: 

Request the image directly from the server (e.g. using cURL or similar), instead of inserting an <img src...>. When you get the image, store it on your server and link to this local version.

Check the Chart API license terms though, to see if you're allowed to do this.

Piskvor