Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

java - How to upload a WAV file using URLConnection

Curretly, I can upload .wav files by using this command in Terminal (MAC):

curl -H 'X-Arg: AccessKey=3f55abc5-2830-027ce-e328-4e74df5a3f8f' --data-binary @audio.wav -H 'Content-Type: audio/wav' http://generic-15327.2-3-11.com/bbb.aaa.eval/abc

I want to do the same from Android. So far I have implemented an AsyncTask with the URLConnection inside, I send the headers and everything, except the wave file. Get a json response telling that no file was uploaded, obviously, but so far so good, I know I implemented the headers and connectivity correctly. Now, I want to upload the .wav file to wrap everything up, but I am a bit lost here. How can I upload a .wav file in Android, by using URLConnection ??? Below is my code, it is inside an AsyncTask which I will not put, to keep things short:

         URL obj = new URL(BASE_URL);
                        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

                        conn.setRequestProperty("X-Arg", "AccessKey=3fcb4985-2830-07ce-e998-4e74df5a3f8f");
                        conn.setRequestProperty("Content-Type", "audio/wav");
                        conn.setRequestMethod("POST");
                        conn.setDoInput(true);
                        conn.setDoOutput(true);

                        String wavpath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/audio.wav";
                        File wavfile = new File(wavpath);
                        boolean success = true;
                        if (wavfile.exists()) {
                            app.loge("**** audio.wav DETECTED");
                        }
                        else{
                            app.loge("**** audio.wav MISSING");
                        }
                     conn.connect();

    //CODE TO UPLOAD THE FILE SHOULD GO HERE!!

                    int responseCode = conn.getResponseCode();
                    app.logy("POST Response Code : " + responseCode);

//Fetch response JSON
                    if (responseCode == HttpURLConnection.HTTP_OK) { //success
                        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        String inputLine;
                        StringBuffer response = new StringBuffer();

                        while ((inputLine = in.readLine()) != null) {
                            response.append(inputLine);
                        }
                        in.close();
                        app.loge(response.toString());
                        result = 1;
                    } else {
                        app.loge("POST FAILED");
                        result = 0;
                    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I finally found a way to do upload wav files. Some servers have slightly different ways of accepting or rejecting an upload request. In this other question URLConnection always returns 400 : Bad Request when I try to upload a .wav file I was trying to accomplish this same task on a different server, and proved to be more complicated than the one I am about to share in this answer, but take a look at it if you still cant make things work. There is no short way of directly "translating" a CURL request into java without messing with the NDK. For this question, this is the code that worked for me:

final String ASR_URL="http:..... ";
public class curlAudioToWatson extends AsyncTask<String, Void, String> {
    String asrJsonString="";
    @Override
    protected String doInBackground(String... params) {
        String result = "";
        try {
            loge("**** UPLOADING .WAV to ASR...");
            URL obj = new URL(ASR_URL);
            HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
            conn.setRequestProperty("X-Arg", "AccessKey=3fvfg985-2830-07ce-e998-4e74df");
            conn.setRequestProperty("Content-Type", "audio/wav");
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            String wavpath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/my AppFolder/"+StorageUtils.AUDIO_FILE_NAME+".wav"; //audio.wav";
            File wavfile = new File(wavpath);
            boolean success = true;
            if (wavfile.exists()) {
                loge("**** audio.wav DETECTED: "+wavfile);
            }
            else{
                loge("**** audio.wav MISSING: " +wavfile);
            }

            String charset="UTF-8";
            String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
            String CRLF = "
"; // Line separator required by multipart/form-data.

            OutputStream output=null;
            PrintWriter writer=null;
            try {
                output = conn.getOutputStream();
                writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
                byte [] music=new byte[(int) wavfile.length()];//size & length of the file
                InputStream             is  = new FileInputStream       (wavfile);
                BufferedInputStream bis = new BufferedInputStream   (is, 16000);
                DataInputStream dis = new DataInputStream       (bis);      //  Create a DataInputStream to read the audio data from the saved file
                int i = 0;
                copyStream(dis,output);
            }
            catch(Exception e){

            }

            conn.connect();

            int responseCode = conn.getResponseCode();
            logy("POST Response Code : " + responseCode + " , MSG: " + conn.getResponseMessage());

            if (responseCode == HttpURLConnection.HTTP_OK) { //success
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                loge("***ASR RESULT: " + response.toString());


                JSONArray jresponse=new JSONObject(response.toString()).getJSONObject("Recognition").getJSONArray("NBest");
                asrJsonString=jresponse.toString();

                for(int i = 0 ; i < jresponse.length(); i++){
                    JSONObject jsoni=jresponse.getJSONObject(i);
                    if(jsoni.has("ResultText")){
                        String asrResult=jsoni.getString("ResultText");
                        //ActionManager.getInstance().addDebugMessage("ASR Result: "+asrResult);
                        loge("*** Result Text: "+asrResult);
                        result = asrResult;
                    }
                }
                loge("***ASR RESULT: " + jresponse.toString());

            } else {
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                loge("POST FAILED: " + response.toString());
                result = "";
            }
        } catch (Exception e) {
            logy("HTTP Exception: " + e.getLocalizedMessage());
        }
        return result; //"Failed to fetch data!";
    }

    @Override
    protected void onPostExecute(String result) {
        if(!result.equals("")){
            logy("onPostEXECUTE SUCCESS, consuming result");
            sendTextInputFromUser(result);
            ActionManager.getInstance().addDebugMessage("***ASR RESULT: "+asrJsonString);
            runOnUiThread(new Runnable() {
                @Override 
                public void run() { 

               } 
           });
        }else{
            logy("onPostEXECUTE FAILED");
        }
    }
}


public void copyStream( InputStream is, OutputStream os) {
    final int buffer_size = 4096;
    try {

        byte[] bytes = new byte[buffer_size];
        int k=-1;
        double prog=0;
        while ((k = is.read(bytes, 0, bytes.length)) > -1) {
            if(k != -1) {
                os.write(bytes, 0, k);
                prog=prog+k;
                double progress = ((long) prog)/1000;///size;
                loge("UPLOADING: "+progress+" kB");
            }
        }
        os.flush();
        is.close();
        os.close();
    } catch (Exception ex) {
        loge("File to Network Stream Copy error "+ex);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...