我在java中向PHP发布了一个表单,但在Ubuntu18.10中没有响应
作为标题,我想用Java实现一个Web服务器,唯一的问题是我需要在login.php上发布一个表单,然后得到响应。 下面的代码是如何将数据发布到PHP的我在java中向PHP发布了一个表单,但在Ubuntu18.10中没有响应,java,php,http,post,server,Java,Php,Http,Post,Server,作为标题,我想用Java实现一个Web服务器,唯一的问题是我需要在login.php上发布一个表单,然后得到响应。 下面的代码是如何将数据发布到PHP的 URL url = new URL("http://127.0.0.1:6789" + req.uri); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Convert string to byte array, as it should be sen
URL url = new URL("http://127.0.0.1:6789" + req.uri);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Convert string to byte array, as it should be sent
// req.form is the form data to post to the login.php
byte[] postDataBytes = req.form.getBytes(StandardCharsets.UTF_8);
// set the form from request as the post data to PHP
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.getOutputStream().write(postDataBytes);
// get response
int code = conn.getResponseCode();
InputStream is;
if (code == 200) {
is = conn.getInputStream();
fillHeaders(Status._200_);
} else {
is = conn.getErrorStream();
fillHeaders(Status._404_);
}
// get response conetent length from login.php
int length = conn.getContentLength();
login.php的内容非常简单:
<?php
echo 'User name is:' . $_POST['loginName'];
?>
这意味着我无法从login.php获得响应
那么我如何改变ubuntu的代码或环境(可能是php的版本?)来解决这个问题呢
Thx。XD如果java是服务器,PHP是客户端,那么应该用java打开监听连接
ServerSocket server = new ServerSocket(8080);
System.out.println("Listening for connection on port 8080 ....");
while (true) {
Socket clientSocket = server.accept();
InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
BufferedReader reader = new BufferedReader(isr);
String line = reader.readLine();
while (!line.isEmpty()) {
System.out.println(line); line = reader.readLine();
}
}
这个问题清楚地描述了从java到PHP的请求,而不是相反。无论哪种方式,您都不会打开原始套接字连接来接收HTTP请求……有更好的方法来启动webserverADyson说的没错。Thx,但是我仍然没有解决这个问题的方法。使用
PHPCGI
可以解决这个问题。
ServerSocket server = new ServerSocket(8080);
System.out.println("Listening for connection on port 8080 ....");
while (true) {
Socket clientSocket = server.accept();
InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
BufferedReader reader = new BufferedReader(isr);
String line = reader.readLine();
while (!line.isEmpty()) {
System.out.println(line); line = reader.readLine();
}
}