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

时间:2015-10-10 19:07:38

标签: java node.js post

我用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);

这是一个减少版本,但我所看到的只是获取请求。我可以看到Java正在连接和发布数据,就像我启动Node.js时一样,只有当我启动Node.js时,Java应用程序才会连接到URL,然后在帖子之间发生第二次延迟时启动POSTING,我终止节点,然后它停止发布并重新启动节点导致帖子恢复。

2 个答案:

答案 0 :(得分:0)

您的节点应用永远不会向客户发送响应。您发送了大量请求,但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();

答案 1 :(得分:0)

修复了,它是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);;
    }