Java – Downloading a Website
Recently I had to figure out how to access a specific url on my server from within Java to update the scores for a Java based game. I figured out that the easiest way to to this is to download the whole contents of the page. This simulates you actually gling to the site on a browser to execute the url. Also, you can work with the html contents, and even out put it back as an actual file with modifications.
The use of this requires 2 imports:
import java.net.*; import java.io.*;
And then the code, I just have mine in a function:
public void doURL(){ try{ URL scoreserv= new URL("http://google.com"); URLConnection ss = scoreserv.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(ss.getInputStream())); }catch(Exception e){ } }
That will download the contents of google.com into the BufferedReader, but can easily be changed to allow your Java app to do server related things if the php file is setup correctly to take parameters. (Be sure to read SQL and general input safety)




Reader Comments