【问题标题】:Send the data of edittextfield from android to node.js将edittextfield的数据从android发送到node.js
【发布时间】:2016-02-19 09:09:29
【问题描述】:

我的后端代码,即 node.js 运行良好我已经通过使用邮递员以 json 格式发送一些数据来检查它,它们被存储在我的 db(mongodb) 中,现在我想从 edittextfield android 获取数据并发送它到服务器。我编写的代码正在访问服务器,但我没有获取数据。我已经检查了 console.log(req) 它没有包含我发送的数据。
而且我看过以前被问过的与此相关的帖子,但对我没有帮助

这里是安卓代码

          private static String url_create_product =   
                                   "http://192.168.1.3:3000/contactlist"; 

          protected String doInBackground(String... args) {
            String name = inputFullName.getText().toString();
            String email = inputEmail.getText().toString();
            String password = inputPassword.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("email", email));
            params.add(new BasicNameValuePair("password", password));


            Log.d("params",params.toString());

            JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                    "POST", params);


            Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {

                    Intent i = new Intent(getApplicationContext(), 
                     MainActivity.class);
                    startActivity(i);


                    finish();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;

        }

这里是 node.js 代码

       app.post('/contactlist', function (req, res) {
         console.log("i am going to insert");
        console.log(req);
        console.log(req.body);
        console.log(req.query);
        console.log(req.params);

          db.users.insert(req.body, function(err, doc) {
                                          res.json(doc);
               console.log(doc)
           });
      });

这是错误 the errors that i am getting

makehttprequest 方法代码是 public JSONObject makeHttpRequest(String url, String 方法, 列出参数){

    try {// check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
     try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

服务器错误

    Error: invalid json
    at parse (E:\app10 - Copy\node_modules\body-     parser\lib\types\json.js:79:15)
     at E:\app10 - Copy\node_modules\body-parser\lib\read.js:102:18
at done (E:\app10 - Copy\node_modules\body-parser\node_modules\raw-body\index.js:248:14)
at IncomingMessage.onEnd (E:\app10 - Copy\node_modules\body-parser\node_modules\raw-body\index.js:294:7)
at IncomingMessage.g (events.js:180:16)
at IncomingMessage.EventEmitter.emit (events.js:92:17)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)

安卓错误

    7292-7312/com.example.malli.login2 E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xb9ac4360
     7292-8793/com.example.malli.login2 E/JSON Parser﹕ Error parsing data org.json.JSONException: Value Error of type java.lang.String cannot be converted to JSONObject

【问题讨论】:

  • 您是否在客户端中将内容类型设置为“application/json”?
  • 不,我没有这样做
  • @SelçukCihan 可以告诉我设置内容类型的代码
  • 我需要查看您的 jsonParser 对象的代码,特别是 makeHttpRequest 方法;内容类型将在那里设置。
  • @SelçukCihan 我在 makeHttpRequest 方法中添加了标头代码,但不幸的是,在此应用程序在这里停止后,代码尝试 {if(method == "POST"){ DefaultHttpClient httpClient = new DefaultHttpClient() ;HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); httpPost.setHeader("内容类型", "应用程序/json"); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent()}

标签: javascript android json node.js mongodb


【解决方案1】:

试试这个

 JSONObject params= new JSONObject();

    try {
        params.put("name", name);     
        params.put("email", email); 
        params.put("password", password);

        HttpPost httpost = new HttpPost(url);

        httpost.setEntity(new StringEntity(params.toString()));
        httpost.setHeader("Accept", "application/json");
        httpost.setHeader("Content-type", "application/json");

        Toast.makeText(this, params.toString(), Toast.LENGTH_LONG).show();

    } catch (JSONException e) {
        e.printStackTrace();
        Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
    } 

//Other code

console.log(req.body); 在服务器上的输出是什么?

【讨论】:

  • @user3923278,查看编辑...我添加了new StringEntity(json.toString()); 以将正文发布为JSON。登录req.body服务器端时的输出是什么?
  • 现在我得到了错误 android 转换结果中的错误 java.lang.NullPointerException: lock == null /com.example.malli.login2 E/JSON Parser: 解析数据时出错 org.json.JSONException :在 /com.example.malli.login2 E/Surface 的字符 0 处输入结束:getSlotFromBufferLocked:未知缓冲区:0xb9b7fdd0
  • 更新为使用JSONObject而不是Map,因此可以将多种数据类型添加到body
  • console.log(req.body) 的输出; { 邮箱:'qq',姓名:'QQ',密码:'11' }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
  • 2019-03-11
  • 2023-03-25
  • 1970-01-01
  • 2020-09-20
  • 2019-04-29
  • 1970-01-01
相关资源
最近更新 更多