Java 使用HttpURLConnection发送post

Java 使用HttpURLConnection发送post,java,node.js,Java,Node.js,我有一个node.js,它使用2个参数(name和pass)等待post: 我试图通过简单的java应用程序发送带有2个参数的post,但我看不到它是否到达node.js 我错过了什么 java代码: public static void main(String[] args) { URL url; HttpURLConnection urlConnection = null; try { url = new URL("http://83.63.118.1

我有一个node.js,它使用2个参数(name和pass)等待post:

我试图通过简单的java应用程序发送带有2个参数的post,但我看不到它是否到达node.js

我错过了什么

java代码:

public static void main(String[] args) {
    URL url;
    HttpURLConnection urlConnection = null;
    try {
        url = new URL("http://83.63.118.111:31011/login.html");

        urlConnection = (HttpURLConnection) url.openConnection();               
        urlConnection.setReadTimeout(10000);
        urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

        urlConnection.setConnectTimeout(10000);
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);

        OutputStream os = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));          
        String str = "name='root'&pass='123456'";
        //System.out.print(str);
        writer.write(str);
        writer.flush();
        Thread.sleep(100);
        writer.close();
        os.close();       
}           

开始发送数据(发送和停止)时,您的代码将关闭

你应该等它完成

在writer.flush()之后添加代码

示例获取
响应

BufferedReader in = new BufferedReader(
        new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();

while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
或者直接获取
响应代码

int responseCode = urlConnection.getResponseCode();
您的程序等待发送请求成功或失败

我想你用的是
Thread.sleep(100)等待发送请求,但它会停止线程(不向服务器发送数据)


你的代码有
req.body
,Express.js没有,需要使用中间件。

我同意在这里睡觉是不对的(通常是这样)。相反,程序应该肯定地等待HTTP响应,不管它是否读取详细信息。获取响应代码是一种很好的方法。(客户端怎么知道程序是否成功呢?)但是,在尝试获取响应之前,可能需要关闭连接的输出流,而不仅仅是刷新连接的输出流。现在我在服务器上看到了帖子,但似乎req.body是空的。为什么?
req.body
未定义。如果您想拥有
req.body
,请使用模块
body解析器
int responseCode = urlConnection.getResponseCode();