繁体   English   中英

从Java发布数据并在node.js应用程序中接收

[英]Posting data from Java and receiving in node.js applicaiton

我用Java编写了一个演示,该演示每秒发布一次数据:

public static void main(String[] arystrArgs) {
    //Get Operating System name and version     
    String strOSname = System.getProperty("os.name").toLowerCase();

    //Display application title and what it is running on       
    System.out.println("Java Data Posting Demo");
    System.out.println("Build date: " + BUILD_DATE + ", Version: " + VERSION_NO);
    System.out.println("Running on: " + strOSname.substring(0, 1).toUpperCase() 
                                      + strOSname.substring(1).toLowerCase());
    //Post data to server
    HttpURLConnection conn = null;

    while( true ) {
        try {
                Thread.sleep(DELAY_BETWEEN_POSTS);

                URL url = new URL("http://localhost:8080");
                conn = (HttpURLConnection)url.openConnection();

                if ( conn != null ) {
                    //Whatever you wants to post...                 
                    String strPostData = "p1=Hello&p2=" + (new Date()).getTime();

                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-length", Integer.toString(strPostData.length()));
                    conn.setRequestProperty("Content-Language", "en-GB");
                    conn.setRequestProperty("charset", "utf-8");
                    conn.setUseCaches(false);
                    conn.setDoOutput(true);

                    DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
                    dos.writeBytes(strPostData);
                    dos.close();

                    System.out.println("Post to: " + url.toString() + ", data: " + strPostData);
                }
            } catch (InterruptedException|IOException ex) {
                    //ex.printStackTrace();                 
            } finally {
                if ( conn != null ) {
                    conn.disconnect();
                    conn = null;
            }                   
        }
    }
}

我已经编写了一个侦听端口8080的Node.js应用程序,但是在http处理程序中看不到任何POST请求,当我在相同的地址和端口上使用浏览器进行测试时,我只会看到GET请求。

来自node.js应用程序的代码段:

function defaultHandler(request, response) {
    try{
           if ( request.method == "POST" ) {
               var strBody = "";
               request.on("data", function(chunk) {
                   strBody += chunk;
               });

               request.on("end", function() {
                   console.log("Received posted data: " + strBody);
               });
           } else {
                      console.dir(request);
                  }
      } catch( ex ) {
          console.dir(ex);
      }
};

var app = http.createServer(defaultHandler);
app.listen(8080);

这是精简版,但我所看到的只是get请求。 我可以看到Java正在连接和发布数据,因为当我启动Node.js时,只有当我启动Node.js时,Java应用程序才连接到URL,然后在发布之间有第二个延迟地启动POSTING,即终止节点,然后它停止发布并重新启动节点,使发布恢复。

您的Node应用程序从不向客户端发送响应。 您发送了很多请求,但是Java Client从未收到服务器的响应。 您应该在响应时执行end方法。

var http = require('http');

function defaultHandler(request, response) {
    try {
        if (request.method == "POST") {
            var strBody = "";
            request.on("data", function(chunk) {
                strBody += chunk;
            });
            request.on("end", function() {
                console.log("Received posted data: " + strBody);
            });
        } else {
            console.dir(request);
        }

        respone.end(); // for example here

    } catch (ex) {
        console.dir(ex);
    }
};

var app = http.createServer(defaultHandler);
app.listen(8080);

在这里您可以找到文档-https://nodejs.org/api/http.html#http_class_http_serverresponse

我不是Java开发人员,但我认为您可以尝试在连接上使用flush和getResponseCode方法。

conn.setDoOutput(true);

DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(strPostData);
dos.flush();
dos.close();

int responseCode = conn.getResponseCode();

固定,它是Java,我将Java代码修改如下:

    URL url = new URL("http://localhost:8080");
    conn = (HttpURLConnection)url.openConnection();

    if ( conn != null ) {
    //Whatever you wants to post...                 
            String strPostData = "p1=Hello&p2=" + (new Date()).getTime();

            conn.setRequestMethod("POST");
            conn.setRequestProperty("User-Agent", USER_AGENT);
            conn.setRequestProperty("Accept-Language", "en-GB,en;q=0.5");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-length", Integer.toString(strPostData.length()));
            conn.setRequestProperty("Content-Language", "en-GB");
            conn.setRequestProperty("charset", "utf-8");
            conn.setUseCaches(false);
            conn.setDoOutput(true);

            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(strPostData);
            dos.flush();
            dos.close();

            int intResponse = conn.getResponseCode();
            System.out.println("\nSending 'POST' to " + url.toString() + 
                    ", data: " + strPostData + ", rc: " + intResponse);;
    }

暂无
暂无

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

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