简体   繁体   中英

Why isn't my node.js restful api recieving this output stream from Java Android?

I have a class audio sender which makes a connection to the nodejs server and uploads an audio file in POST method mode.

public class AudioSender implements Callable<JSONObject> {

String outputFile;

AudioSender(String fileLocation){
    outputFile=fileLocation;
}

public JSONObject call(){
    URL url = null;
    HttpURLConnection urlConnection = null;
    InputStream audioInputStream=null;
    JSONObject response=null;
    byte buffer[]=new byte[16];
    try {
        url = new URL("http://192.168.0.106:3000/upload");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } finally {
        try {
            urlConnection = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            urlConnection.setDoOutput(true);
            urlConnection.setChunkedStreamingMode(16);
            urlConnection.setRequestProperty("Content-Type","multipart/form-data");
            urlConnection.setRequestProperty("Connection", "Keep-Alive");
            urlConnection.setRequestProperty("Cache-Control", "no-cache");
            urlConnection.setRequestProperty(
                    "Content-Type", "multipart/form-data;boundary=*****");
            try {
                OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
                try {
                    audioInputStream = new BufferedInputStream(new FileInputStream(outputFile));
                    Log.d("hello","audioinputstream");
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {

                    while(audioInputStream.read(buffer)!=-1) {
                        out.write(buffer);
                        Log.d("buffer",buffer.toString());
                    }
                    try {
                        audioInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                StringBuilder total = new StringBuilder();
                while(in.read(buffer)!=-1)
                    total.append(buffer);
                    Log.d("response",total.toString());
                try {
                    response = new JSONObject(total.toString());
                }catch(JSONException e){
                    Log.e("Response Parse Error", "Could not parse malformed JSON");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return response;
}

This is the upload that executes the AudioSender callable.

public void upload() {
    JSONObject response=null;
    AudioSender sender=new AudioSender(outputFile);
    FutureTask<JSONObject> uploadTask=new FutureTask<JSONObject>(sender);
    ExecutorService executorService= Executors.newFixedThreadPool(1);
    executorService.execute(uploadTask);
    Log.d("s","was here");
    while(true){
        if(uploadTask.isDone()){
            try{
                response=uploadTask.get();
            }catch(InterruptedException|ExecutionException e){
                e.printStackTrace();
                Log.e("ee","ee",e.getCause());

            }
        }
    }
}

I pretty much know this isn't node js's fault but here's the server code: app.post('/upload',function(req,res){ console.log("someone called!"); req.on('data',function(chunk){ console.log('res'); console.log(chunk); }); req.on('end',function(){ console.log("done!"); res.send({'name':'sg'}); });});

When I call upload(), the server console prints someone called! done!

I was debugging and found that indeed I am receiving the responded json object from the server. And I don't know if out.write(buffer) is doing the job, but debugging it shows that the buffer value is changing and is in par with my audio file's size.

Please do not suggest using ION or anything else.

I solved the problems by setting up the URLConnection as follows:

            boundary = "===" + System.currentTimeMillis() + "===";
            urlConnection.setUseCaches(false);
            urlConnection.setDoOutput(true);    // indicates POST method
            urlConnection.setDoInput(true);
            urlConnection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM