Invoking PHP from Java


Invoking PHP from Java

我正试图从Java程序中调用一些PHP脚本,以便查询/修改数据库。我对数据库完全陌生,不知道发生了什么。

我正在尝试从java中调用以下脚本。

脚本

<?php
include('test.php');
define("HOST", "localhost");
define("USERNAME", "xxxx");
define("PASSWORD", "xxxx");
define("DATABASE", "project_database");
mysql_connect(HOST, USERNAME, PASSWORD);
mysql_select_db(DATABASE);
?>

Java代码

 public static String excutePost(String targetURL, String urlParameters)
    {
      URL url;
      HttpURLConnection connection = null;  
      try {
        //Create connection
        url = new URL(targetURL);
        connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", 
             "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", "" + 
                 Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");  
        connection.setUseCaches (false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        //Send request
        DataOutputStream wr = new DataOutputStream (
                    connection.getOutputStream ());
        wr.writeBytes (urlParameters);
        wr.flush ();
        wr.close ();
        //Get Response  
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer(); 
        while((line = rd.readLine()) != null) {
          response.append(line);
          response.append(''r');
        }
        rd.close();
        return response.toString();
      } catch (Exception e) {
        e.printStackTrace();
        return null;
      } finally {
        if(connection != null) {
          connection.disconnect(); 
        }
      }
    }

目标URL应该是什么??

如果您想调用一个新进程,请参阅java.lang.process.

然而,Java能够通过JDBC直接与数据库对话,这是我强烈推荐的方法。您不必生成一个新的流程,也不必用一种以上的语言来实现您的解决方案,而且您可以使用许多与JDBC相关的框架,使您的数据库访问变得更加容易。

您需要指定页面的链接,可以是'localhost/yourPageInPhp.php

我假设您需要执行脚本,并在Java 中显示其输出