关于Node.js获取用java代码写的HTTP post请求参数的问题(已解决)

关于Node.js获取用java代码写的HTTP post请求参数的问题(已解决)

用Node.js做了一个接口服务器,但是通过以下方式POST过来的参数获取不到,请问该如何获取???

java 代码调用方式如下:

   /*建立HTTPost对象*/
    HttpPost httpRequest = new HttpPost(uriAPI); 
    /*
     * NameValuePair实现请求参数的封装
    */
    List <NameValuePair> params = new ArrayList <NameValuePair>(); 
    params.add(new BasicNameValuePair("u", "沈大海")); 
    params.add(new BasicNameValuePair("p", "123")); 
    try 
    { 
      /* 添加请求参数到请求对象*/
      httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); 
      /*发送请求并等待响应*/
      HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest); 
      /*若状态码为200 ok*/
      if(httpResponse.getStatusLine().getStatusCode() == 200)  
      { 
        /*读返回数据*/
        String strResult = EntityUtils.toString(httpResponse.getEntity()); 
        mTextView1.setText(strResult); 
      } 
      else 
      { 
        mTextView1.setText("Error Response: "+httpResponse.getStatusLine().toString()); 
      } 
    } 
    catch (ClientProtocolException e) 
    {  
      mTextView1.setText(e.getMessage().toString()); 
      e.printStackTrace(); 
    } 
    catch (IOException e) 
    {  
      mTextView1.setText(e.getMessage().toString()); 
      e.printStackTrace(); 
    } 
    catch (Exception e) 
    {  
      mTextView1.setText(e.getMessage().toString()); 
      e.printStackTrace();  
    }

6 回复

关于Node.js获取用Java代码写的HTTP POST请求参数的问题(已解决)

背景

我用Node.js实现了一个接口服务器,用于处理客户端的HTTP POST请求。但是在接收由Java代码发起的POST请求时,发现无法正确获取请求参数。经过排查,我发现问题出在如何正确解析POST请求体中的参数。

Java代码调用方式

Java客户端使用HttpPost对象发送一个带有表单数据的POST请求,具体代码如下:

/* 建立HttpPost对象 */
HttpPost httpRequest = new HttpPost(uriAPI); 

/* 使用NameValuePair实现请求参数的封装 */
List<NameValuePair> params = new ArrayList<NameValuePair>(); 
params.add(new BasicNameValuePair("u", "沈大海")); 
params.add(new BasicNameValuePair("p", "123")); 

try {
  /* 添加请求参数到请求对象 */
  httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); 

  /* 发送请求并等待响应 */
  HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest); 

  /* 若状态码为200 ok */
  if(httpResponse.getStatusLine().getStatusCode() == 200) {
    /* 读取返回的数据 */
    String strResult = EntityUtils.toString(httpResponse.getEntity()); 
    // 这里可以处理返回结果
  } else {
    // 处理错误响应
  }
} catch (ClientProtocolException e) {
  // 处理异常
} catch (IOException e) {
  // 处理异常
} catch (Exception e) {
  // 处理异常
}

Node.js解决方案

在Node.js中,我们需要确保能够正确解析POST请求体中的表单数据。这里我们可以使用body-parser中间件来解析JSON和URL编码的表单数据。首先安装body-parser

npm install body-parser

然后,在Node.js应用中引入并配置body-parser

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

// 解析 application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

// 解析 application/json
app.use(bodyParser.json());

app.post('/api/endpoint', (req, res) => {
  const username = req.body.u;
  const password = req.body.p;

  console.log(`Received username: ${username}`);
  console.log(`Received password: ${password}`);

  res.send({ message: 'Data received successfully' });
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

在这个例子中,我们首先创建了一个Express应用,并添加了body-parser中间件以解析URL编码的表单数据。接着定义了一个POST路由/api/endpoint,该路由会从请求体中提取up参数,并打印出来。最后,向客户端发送一个成功响应。

这样,我们就能够正确地接收并处理由Java代码发起的HTTP POST请求中的参数了。


node部分的代码呢

求解答

url encode的body就用querystring解析。。 var body = ‘’; req.on(‘data’, function(data) {body += data}); req.on(‘end’, function() { require(‘querystring’).parse(body); });

问题解决了,加了如下:

app.use(bodyParser.urlencoded({ extended: true }));

关于Node.js获取用Java代码写的HTTP POST请求参数的问题(已解决)

问题描述

使用Node.js编写了一个接口服务器,但通过Java代码发送的POST请求参数无法正确获取。Java代码如下:

HttpPost httpRequest = new HttpPost(uriAPI);
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("u", "沈大海"));
params.add(new BasicNameValuePair("p", "123"));

try {
    httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
    HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
    if(httpResponse.getStatusLine().getStatusCode() == 200) {
        String strResult = EntityUtils.toString(httpResponse.getEntity());
        // 显示结果
    } else {
        // 处理错误
    }
} catch (ClientProtocolException | IOException | Exception e) {
    e.printStackTrace();
}

解决方法

在Node.js中,你可以使用body-parser中间件来解析请求体中的表单数据。以下是具体的示例代码:

  1. 安装expressbody-parser中间件:
npm install express body-parser
  1. 在Node.js服务器中配置body-parser以解析表单数据:
const express = require('express');
const bodyParser = require('body-parser');

const app = express();

// 使用body-parser中间件解析表单数据
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/api', (req, res) => {
    console.log(req.body.u); // 输出: 沈大海
    console.log(req.body.p); // 输出: 123
    res.send('Received data');
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

代码解释

  • bodyParser.urlencoded({ extended: true }):这行代码用来解析URL编码的数据(例如表单数据)。extended: true表示使用qs库来解析复杂数据结构。
  • req.body:这是请求体中的数据,包含了所有从客户端发送来的键值对。

以上代码将能够正确接收并处理来自Java代码发送的POST请求参数。

回到顶部