[英]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 : 正如标题所示......当用户单击Java Swing应用程序中的按钮时,我尝试使用以下代码执行PHP脚本:
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()
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();
"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). 你可能想玩回车(取决于操作系统,尝试\\ n,\\ r,或两者的组合)。
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.