简体   繁体   English

我在Java中将表单发布到PHP,但在Ubuntu 18.10中没有响应

[英]I post a form to PHP in java, but no response in Ubuntu 18.10

As the title, I want to implement a Web server by Java, the only problem is that I need post a form to login.php and then get the response. 作为标题,我想用Java实现Web服务器,唯一的问题是我需要发布一个表单到login.php,然后获取响应。 The following code is how I post the data to 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 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();

The content of login.php is very simple: login.php的内容非常简单:

<?php
echo 'User name is:' . $_POST['loginName'];
?>

When I debug this part, I will stall in this line 当我调试这部分时,我会停在这一行

int code = conn.getResponseCode();

That means I cannot get response from login.php 这意味着我无法从login.php获得响应

So how can I change the code or the enviornment of ubuntu (maybe the version of php?) to solve this problem. 因此,如何更改代码或ubuntu的环境(也许是php版本?)来解决此问题。

Thx. 谢谢。 XD XD

If java is the server and PHP is a client you should open listening connection in java. 如果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(); 
} 
}


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM