我正在尝试将一些数据从 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页面还不够简单吗?
编辑:我试图通过在文件中写入发布的变量来查看 php 页面是否正在接收某些内容。但是里面什么也没写。
$file = 'debug.txt';
echo file_put_contents($file, $_POST['var']);
这是我得到的例外..
java.net.SocketException: Connection reset