代码之家  ›  专栏  ›  技术社区  ›  Brad

如何从Java代码调用PHP脚本?

  •  3
  • Brad  · 技术社区  · 14 年前

    标题上说…当用户单击JavaSwing应用程序中的一个按钮时,我尝试使用下面的代码来执行PHP脚本:

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

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

    2 回复  |  直到 12 年前
        1
  •  5
  •   Cyrille    12 年前

    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
    }
    
        2
  •  1
  •   Evan Mulawski    14 年前
    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();