Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i call a PHP script from Java code?

Tags:

java

php

execute

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 ?

like image 874
Brad Avatar asked Mar 09 '26 19:03

Brad


1 Answers

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
}
like image 121
Gareth Davis Avatar answered Mar 12 '26 08:03

Gareth Davis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!