为什么js服务器没有收到HTTP发布请求?

时间:2018-07-06 17:12:00

标签: javascript android node.js http

我正在编写一个Android应用,该应用通过HTTP将.wav文件发送到PC上运行的nodeJs服务器。节点Js服务器在收到POST请求时仅将消息打印到屏幕上。它还打印接收到的文件的内容。在Android方面,单击按钮时会向服务器发出包含该文件的POST请求。问题在于单击该按钮时,服务器永远不会收到任何东西。我尝试使用POSTman软件发出POST请求,并且工作正常。

android代码:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btn = findViewById(R.id.btnSend);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("MY TAG: ", "SENDING....");
                send();
                Log.d("MY TAG: ", "SENT.");
            }
        });

    }

    void send(){

        String url = "http://"my ip goes here":4000/extract_indicators/audio/3";
        File exStore = Environment.getExternalStorageDirectory();
        File file = new File(exStore.getAbsolutePath() + "/AudioRecord/recording0.wav");
        try {
            HttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost(url);

            InputStreamEntity reqEntity = new InputStreamEntity(
                    new FileInputStream(file), -1);
            reqEntity.setContentType("binary/octet-stream");
            reqEntity.setChunked(true); // Send in multiple parts if needed
            httppost.setEntity(reqEntity);
            HttpResponse response = httpclient.execute(httppost);
            //Do something with response...
            Log.d("HTTP ", "RESPONSE: " + response);

        } catch(Exception e) {
            // show error
        }
    }
}

NodeJs代码:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var multer = require('multer');
const fs = require('fs');
const wav = require('wav');
let upload = multer();

app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.raw({ type: 'audio/wav', limit: '50mb' }));

app.post('/extract_indicators/audio/:user_id', upload.any(), function(req, res) {
    console.log("RECIEVED AUDIO TO EXTRACT INDICATORS: ", req.body);
    let formData = req.body;
    let files = req.files;
    //fs.writeFileSync('audiotest.wav', req.files[1].buffer);
    console.log('form data', formData, 'file' , files);
    res.sendStatus(200);
});

app.listen(4000);

按下按钮时的Logcat:

D/ViewRootImpl@ad416c[MainActivity]: ViewPostImeInputStage processPointer 0
D/ViewRootImpl@ad416c[MainActivity]: ViewPostImeInputStage processPointer 1
D/MY TAG:: SENDING....
D/MY TAG:: SENT.

编辑:

这是原始问题的第一个答案之后的已编辑代码。但是,我仍然遇到同样的问题。

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btn = findViewById(R.id.btnSend);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Log.d("MY TAG: ", "SENDING....");
                new wavSender().execute();
                Log.d("MY TAG: ", "SENT.");
            }
        });

    }

    private class wavSender extends AsyncTask<String, Void, String> {


        public wavSender() {
        }

        @Override
        protected String doInBackground(String... strings) {

            String url = "http://my ip goes here:4000/extract_indicators/audio/3";
            File exStore = Environment.getExternalStorageDirectory();
            File file = new File(exStore.getAbsolutePath() + "/AudioRecord/recording0.wav");
            try {
                HttpClient httpclient = new DefaultHttpClient();

                HttpPost httppost = new HttpPost(url);

                InputStreamEntity reqEntity = new InputStreamEntity(
                        new FileInputStream(file), -1);
                reqEntity.setContentType("binary/octet-stream");
                reqEntity.setChunked(true); // Send in multiple parts if needed
                httppost.setEntity(reqEntity);
                HttpResponse response = httpclient.execute(httppost);
                //Do something with response...
                Log.d("HTTP ", "RESPONSE: " + response);

            } catch(Exception e) {
                // show error
            }
            return null;
        }

        @Override
        protected void onPostExecute(String temp) {
            Log.d("MY TAG", "POST EXECUTE HAS RAN");

        }
    }
}

1 个答案:

答案 0 :(得分:1)

您可能正在主线程中执行网络功能,它可能会引发错误,但是您使用try-catch禁止了它。您可以使用AsyncTask进行网络通话,请参考以下链接以了解如何使用它:https://developer.android.com/reference/android/os/AsyncTask