views:

67

answers:

2

Hello ,

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 ?

+1  A: 

Think your 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
}
Gareth Davis
Thanks Gareth ... It now works fine. I first thought that connect() will automatically call the url and execute it directly since i'm using HttpURLConnection and not URLConnection.
Brad
No worries. As you can see from my second example, calls to connect() are actually optional. to be honest if you are doing anything other than the simplest thing you might want to consider using apache's HttpClient
Gareth Davis
A: 
final URL url = new URL("http://domain.com/script.php");
final InputStream inputStream = new InputStreamReader(url);
final BufferedReader reader = new BufferedReader(inputStream).openStream();

String line, response = "";

while ((line = reader.readLine()) != null)
{
    response = response + "\r" + line;
}

reader.close();

"response" will hold the text of the page. You may want to play around with the carriage return (depending on the OS, try \n, \r, or a combination of both).

Hope this helps.

Evan Mulawski