How can i call a PHP script from Java code?

吃可爱长大的小学妹 提交于 2019-12-07 12:00:40

问题


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 ?


回答1:


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
}



回答2:


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.



来源:https://stackoverflow.com/questions/4023533/how-can-i-call-a-php-script-from-java-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!