两个程序间通信(三):http

转载来源:http://blog.sina.com.cn/s/blog_a1304cff0101a6j4.html

假设你的java项目要和一个php项目通信,你想传递变量过去,那么可采用如下式:

HttpClient httpClient = new HttpClient();    
PostMethod post = new PostMethod(url);    //php端提供的接收方法url  
post.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded;charset=gb2312");   

NameValuePair[] param = {   
        new NameValuePair("param1",value1),   
        new NameValuePair("param2",value2),   
    };      

post.setRequestBody(param);      
httpClient.executeMethod(method);   
String response = method.getResponseBodyAsString();   //用流接收更好。         
post.releaseConnection();

这样,将参数传递过去,在php端,建立一个方法,暴露给外部,即可以通过url访问到该方法即可。php方法return的值就是response的值。注意如果不指定charset,则默认字符集是iso-8859-1。如果php端要向java项目传递数据,那么php端要用到curl post数据过来,注意要设置header,主要指定字符集,否则中文乱码,java端要将iso-8859-1转成utf-8.在java端,新建一个servlet即可,它的dopost方法,将接收php curl post过来的数据。在回写的时候,这样:

response.getWriter().write("123456");        
response.getWriter().flush();

php端得到123456; 因为2个项目有共同的数据格式http,所以可以这样通信,这就是协议的力量。共同遵守此数据格式。其实用http,数据要经过封装,最高效还是socket,php端也可以进行socket操作,似乎越底层的效率越高。

你可能感兴趣的:(两个程序间通信(三):http)