如何从 Java 执行 PHP 脚本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/655620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:28:13  来源:igfitidea点击:

How can I execute a PHP script from Java?

javaphp

提问by trivunm

I have a php script which is executed over a URL. (e.g. www.something.com/myscript?param=xy)

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

When this script is executed in a browser it gives a coded result, a negative or positive number.

当这个脚本在浏览器中执行时,它会给出一个编码结果,一个负数或正数。

I want to execute this script from Java code(J2EE) and store that result in some object.

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

I'm trying to use httpURLConnectionfor that. I establish a connection but can not fetch the result. I'm not sure if I execute the script at all.

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

采纳答案by Mork0075

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();
    }
}

This snippet is from the offical Java tutorial (http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html). This should help you.

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

回答by Pablo Santa Cruz

If your J2EE app is deployed on the same server the PHP script is on, you can also execute it directly through as an independent process like this:

如果您的 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();
  }

You will pay the overhead of creating and executing a process, but you won't be creating a network connection every time you need to execute the script. I think that depending on the size of your output, one will perform better than the other.

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

回答by Dr.Pil

If you are trying to run it over HTTP I would recommend the Apache Commons HTTP Clientlibraries. They make it incredibly easy to perform this type of task. For example:

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

    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);

回答by samaitra

On the related note if you are trying to execute a php script from a java program , you may refer the following code

在相关说明中,如果您尝试从 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();

回答by MansoorShaikh

I faced exactly the same issue today. For me, that thing which worked was URLEncoding the PHP script parameters using java.net.URLEncoder.encode method.

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

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;

回答by Amol Suryawanshi

I faced similar situation where I need to call PHP function from java code and I have used below code to achieve this. In below code "/var/www/html/demo/demo.php" is the PHP file name and callToThisFunction() is the PHP function name. Hope this helpful for someone.

我遇到了类似的情况,我需要从 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();

    }