How can i call a PHP script from Java code?
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 ?
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
}
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.
精彩评论