轉(zhuǎn)載來源:http://blog.sina.com.cn/s/blog_a1304cff0101a6j4.html
假設(shè)你的java項(xiàng)目要和一個(gè)php項(xiàng)目通信,你想傳遞變量過去,那么可采用如下式:
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();
這樣,將參數(shù)傳遞過去,在php端,建立一個(gè)方法,暴露給外部,即可以通過url訪問到該方法即可。php方法return的值就是response的值。注意如果不指定charset,則默認(rèn)字符集是iso-8859-1。如果php端要向java項(xiàng)目傳遞數(shù)據(jù),那么php端要用到curl post數(shù)據(jù)過來,注意要設(shè)置header,主要指定字符集,否則中文亂碼,java端要將iso-8859-1轉(zhuǎn)成utf-8.在java端,新建一個(gè)servlet即可,它的dopost方法,將接收php curl post過來的數(shù)據(jù)。在回寫的時(shí)候,這樣:
response.getWriter().write("123456");
response.getWriter().flush();
php端得到123456; 因?yàn)?個(gè)項(xiàng)目有共同的數(shù)據(jù)格式http,所以可以這樣通信,這就是協(xié)議的力量。共同遵守此數(shù)據(jù)格式。其實(shí)用http,數(shù)據(jù)要經(jīng)過封裝,最高效還是socket,php端也可以進(jìn)行socket操作,似乎越底層的效率越高。