如何在java程序中调用php文件

Python029

如何在java程序中调用php文件,第1张

 public String execPHP(String scriptName, String param) {

        StringBuilder output = new StringBuilder()

        BufferedReader input = null

        String phpPath = "D:/xampp/php/php.exe"

        try {

            String line

            Process p = Runtime.getRuntime().exec(phpPath + " " +scriptName + " " + param)

            input = new BufferedReader(new InputStreamReader(p.getInputStream()))

            while ((line = input.readLine()) != null) {

                output.append(line)

//                p.destroy()//根据系统不同可能需要

            }

            p.destroy()

        } catch (Exception err) {

            err.printStackTrace()

        }finally{

            if(input != null){

                try {

                    input.close()

                } catch (IOException e) {

                    e.printStackTrace()

                }

            }

        }

        return output.toString()

    }

//调用php算法

conclusion = runPHP.execPHP(ALGORITHM_RESIDUES_URL,imageResiduesId)

//php接收

$id = $argv[1]

因为此方法是java开进程直接调用php,因此是以内存方式传参

import java.io.BufferedInputStream

import java.io.BufferedOutputStream

import java.io.BufferedReader

import java.io.InputStreamReader

import java.net.HttpURLConnection

import java.net.URL

import java.nio.charset.Charset

import XmlHelper

public class QXOutStream {

public String outPutStr(String urlStr, String input) throws Exception{

StringBuffer strBuf = new StringBuffer()

String Resulst=""

try{

URL url = new URL(urlStr)

HttpURLConnection con = (HttpURLConnection)url.openConnection()

con.setDoInput(true)

con.setDoOutput(true)

con.setRequestMethod("POST")

con.setAllowUserInteraction(false)

con.setUseCaches(false)

con.setRequestProperty("Accept-Charset", "GBK")

BufferedOutputStream bufOutPut = new BufferedOutputStream(con.getOutputStream())

byte[] bdat = input.getBytes("UTF-8")//解决中文乱码问题

bufOutPut.write(bdat, 0, bdat.length)

bufOutPut.flush()

BufferedInputStream inp = new BufferedInputStream(con.getInputStream())

InputStreamReader in = new InputStreamReader(inp,Charset.forName("GBK"))

BufferedReader bufReador = new BufferedReader(in)

String tempStr = ""

while (tempStr != null) {

strBuf.append(tempStr)

tempStr = bufReador.readLine()

}

Resulst = XmlHelper.getPostNodeText(strBuf.toString(), "OPERATOR_RESULT")//.getPostFirstRowText(strBuf.toString(), "OPERATOR_RESULT")

}

catch (Exception e) {

//System.err.println("Exception:"+e.toString())

throw e

//return "N"

}

finally{

return Resulst

}

}

}

你可以参考这个例子调用php 的api接口,这里面的urlStr就是你调用php的api url接口

接口返回的参数格式一般是由客户端的需要来设置,至于你说的这些,一般是封装成一个对象,然后将对象转换成Json字符串返回,客户端接收到Json字符串后,再转换成对象来解析需要的信息就可以了。