如何从Java代码调用PHP脚本?
正如标题所示……当用户单击Java Swing应用程序中的按钮时,我尝试使用以下代码执行PHP脚本:
URL url = new URL( "http://www.mywebsite.com/my_script.php" ); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect();
但没有任何反应…… 有什么不对吗?
我想你错过了下一步,例如:
InputStream is = conn.getInputStream();
HttpURLConnection
基本上只打开connect
上的套接字,以便做一些你需要做的事情,比如调用getInputStream()
或更好的仍然是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();
“回复”将保留页面文本。 您可能想要回车(取决于操作系统,尝试\ n,\ r,或两者的组合)。
希望这可以帮助。