3

正如标题所说...当用户单击我的 Java Swing 应用程序中的按钮时,我尝试使用以下代码执行 PHP 脚本:

URL url = new URL( "http://www.mywebsite.com/my_script.php" );
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();

但是什么也没有发生……有什么问题吗?

4

2 回答 2

6

我认为您错过了下一步,例如:

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
}
于 2010-10-26T12:20:24.970 回答
1
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 或两者的组合)。

希望这可以帮助。

于 2010-10-26T12:30:17.910 回答