Can anyon开发者_StackOverflow中文版e 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.
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.
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.
精彩评论