[英]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中顯示其輸出
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.