我正在尝试将一些数据从JSP页面发送到PHP页面(它应该执行一些代码并返回成功消息)。 我正在使用这个java函数进行一些测试:
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));
现在如果我运行页面,我得到响应“null”,并且没有执行php页面中的代码。
难道我做错了什么?如何让php页面运行代码呢?
是不是简单的echo $_POST['var']
足以将数据发送回jsp页面?
$file = 'debug.txt';
echo file_put_contents($file, $_POST['var']);
这是我得到的例外......
java.net.SocketException: Connection reset
答案 0 :(得分:0)
不,echo
还不够。将$_POST['var']
放入文本文件并提供更新的文本文件(每次需要跟踪$_POST['var']
时编辑文本文件)。或者,您可以将其放在某个数据库中并检查更改。