0
我想從JSP頁面發送一些數據到PHP(它應該執行一些代碼並返回成功消息)。 我使用這個Java功能,使一些測試:發送POST數據從JSP頁面到遠程PHP服務器(並得到答案)
public String excutePost(String targetURL, String urlParameters)
{
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream());
wr.writeBytes (urlParameters);
wr.flush();
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
String urlParameters =
"var=" + URLEncoder.encode("varcontent", "UTF-8");
out.println(excutePost("remoteurl",urlParameters));
現在,如果我運行的頁面我得到的迴應「零」,並沒有在PHP頁面的代碼被執行。 我做錯了什麼?我怎樣才能讓PHP頁面運行其中的代碼? 是不是一個簡單的echo $_POST['var']
足以發送數據返回到jsp頁面?
編輯:我試圖看看如果php頁面正在接收的東西通過寫入文件中的張貼變量。但是沒有寫入任何內容。
$file = 'debug.txt';
echo file_put_contents($file, $_POST['var']);
,這裏是我得到的例外..
java.net.SocketException: Connection reset
好的謝謝...但我很確定,該網頁是根本沒有達到該發佈數據..任何想法,爲什麼它不是發送數據? – nowhere
通過在文本文件中放置'$ _POST ['var']'並回顯文本文件的內容來檢查它是否到達。 – 2013-02-05 12:41:07
我試過了:'code' $ file ='debug.txt'; echo file_put_contents($ file,$ _POST ['var']);現在我確定發佈的數據沒有被php頁面接收到。 java頁面有什麼問題嗎? – nowhere