如何从Java执行PHP脚本?

时间:2009-03-17 19:06:02

标签: java php

我有一个通过URL执行的php脚本。 (例如www.something.com/myscript?param=xy)

当在浏览器中执行此脚本时,它会提供编码结果,负数或正数。

我想从Java代码(J2EE)执行此脚本,并将结果存储在某个对象中。

我正在尝试使用httpURLConnection。 我建立连接但无法获取结果。我不确定我是否执行该脚本。

6 个答案:

答案 0 :(得分:11)

public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        URL yahoo = new URL("http://www.yahoo.com/");
        URLConnection yc = yahoo.openConnection();
        BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                yc.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null) 
            System.out.println(inputLine);
        in.close();
    }
}

此片段来自官方Java教程(http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html)。这应该对你有帮助。

答案 1 :(得分:10)

如果您的J2EE应用程序部署在PHP脚本所在的同一服务器上,您也可以通过以下独立过程直接执行它:

  public String execPHP(String scriptName, String param) {
    try {
      String line;
      StringBuilder output = new StringBuilder();
      Process p = Runtime.getRuntime().exec("php " + scriptName + " " + param);
      BufferedReader input =
        new BufferedReader
          (new InputStreamReader(p.getInputStream()));
      while ((line = input.readLine()) != null) {
          output.append(line);
      }
      input.close();
    }
    catch (Exception err) {
      err.printStackTrace();
    }
    return output.toString();
  }

您将支付创建和执行流程的开销,但每次需要执行脚本时都不会创建网络连接。我认为根据输出的大小,一个会比另一个表现更好。

答案 2 :(得分:9)

如果您尝试通过HTTP运行它,我会推荐Apache Commons HTTP Client 库。它们使执行此类任务非常容易。例如:

    HttpClient http = new HttpClient();
    http.setParams(new HttpClientParams());
    http.setState(new HttpState());

    //For Get
    GetMethod get = new GetMethod("http://www.something.com/myscript?param="+paramVar);
    http.executeMethod(get);

    // For Post
    PostMethod post = new PostMethod("http://www.something.com/myscript");
    post.addParameter("param", paramVar);
    http.executeMethod(post);

答案 3 :(得分:1)

在相关说明中,如果您尝试从java程序执行php脚本,可以参考以下代码

        Process p = Runtime.getRuntime().exec("php foo.php");

        p.waitFor();

        String line;

        BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        while((line = error.readLine()) != null){
            System.out.println(line);
        }
        error.close();

        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while((line=input.readLine()) != null){
            System.out.println(line);

        }

        input.close();

        OutputStream outputStream = p.getOutputStream();
        PrintStream printStream = new PrintStream(outputStream);
        printStream.println();
        printStream.flush();
        printStream.close();

答案 4 :(得分:0)

我今天遇到了完全相同的问题。对我来说,有用的东西是使用java.net.URLEncoder.encode方法对PHP脚本参数进行URLE编码。

String sURL = "myURL";
String sParam="myparameters";
String sParam=java.net.URLEncoder.encode(sParam,"UTF-8");
String urlString=sURL + sParam;     
    HttpClient http = new HttpClient();
    try {
        http.getHttpResponse(urlString);
    } catch (AutomationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    http=null;

答案 5 :(得分:0)

我遇到了类似的情况,我需要从Java代码调用PHP函数,并且我已经使用下面的代码来实现这一点。在下面的代码中,“ / var / www / html / demo / demo.php”是PHP文件名,而callToThisFunction()是PHP函数名。希望这对某人有帮助。

public static void execPHP() {

        Process process = null;

        try {

            process = Runtime.getRuntime().exec(new String[]{"php", "-r", "require '/var/www/html/demo/demo.php'; callToThisFunction();"});

            process.waitFor();

            String line;

            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));

            while ((line = errorReader.readLine()) != null) {
                System.out.println(line);
            }

            errorReader.close();

            BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            while ((line = outputReader.readLine()) != null) {
                System.out.println(line);

            }

            outputReader.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        OutputStream outputStream = process.getOutputStream();
        PrintStream printStream = new PrintStream(outputStream);
        printStream.println();
        printStream.flush();
        printStream.close();

    }