How can i call a PHP script from Java code?

Brad picture Brad · Oct 26, 2010 · Viewed 8k times · Source

As the title says ... I have tried to use the following code to execute a PHP script when user clicks a button in my Java Swing application :

URL url = new URL( "http://www.mywebsite.com/my_script.php" );
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();

But nothing happens ... Is there something wrong ?

Answer

Gareth Davis picture Gareth Davis · Oct 26, 2010

I think you're missing the next step which is something like:

InputStream is = conn.getInputStream();

HttpURLConnection basically only opens the socket on connect in order to do something you need to do something like calling getInputStream() or better still getResponseCode()

URL url = new URL( "http://google.com/" );
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if( conn.getResponseCode() == HttpURLConnection.HTTP_OK ){
    InputStream is = conn.getInputStream();
    // do something with the data here
}else{
    InputStream err = conn.getErrorStream();
    // err may have useful information.. but could be null see javadocs for more information
}