0

我有这个 Java 代码

DefaultHttpClient httpclient = new DefaultHttpClient();         
        HttpPost httpPostRequest = new HttpPost(URL);           
        StringEntity se;            
        se = new StringEntity(jsonObjSend.toString());          
        // Set HTTP parameters          
        httpPostRequest.setEntity(se);          
        httpPostRequest.setHeader("Accept", "application/json");            
        httpPostRequest.setHeader("Content-type", "application/json");          
        //httpPostRequest.setHeader("Accept-Encoding", "gzip"); 
        // only set this parameter if you would like to use gzip compression            
        long t = System.currentTimeMillis();            
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest); 

这在 node.js 中

var http = require('http');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
console.log("Entering");


if ( request.method === 'POST' ) {

     // the body of the POST is JSON payload.
     request.pipe(process.stdout);   
     }

});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");

我使用管道在控制台中写入所有内容,以确保我收到数据。我真正想要的是将数据解析回 JSON,然后将其保存在数组中。如何从请求中获取数据?有人有代码示例吗?

谢谢

4

2 回答 2

1
var http = require('http');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
console.log("Entering");


if ( request.method === 'POST' ) {

        // the body of the POST is JSON payload.
        request.pipe(process.stdout);   

        var data = '';
        request.on('data', function(chunk) {
            data += chunk;
        });

        request.on('end', function() {
            try {
                data = JSON.parse(data);
            } catch (e) {
                console.log(e);
            }
        });
    }

});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");
于 2012-08-08T10:08:44.227 回答
0

尝试在您的代码中使用以下概念

        response.on('data', function (chunk)
        {
                var data = chunk.toString();
                var data_val = JSON.parse(data)
          });
于 2013-08-29T07:56:48.393 回答