如何从Java执行PHP脚本?

tri*_*unm 9 php java

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

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

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

我正试图用httpURLConnection它.我建立连接但无法获取结果.我不确定我是否执行该脚本.

Mor*_*075 12

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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


Pab*_*ruz 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();
  }
Run Code Online (Sandbox Code Playgroud)

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


Dr.*_*Pil 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);
Run Code Online (Sandbox Code Playgroud)