如何使用URLConnection上传WAV文件

时间:2015-12-04 13:25:48

标签: java android android-studio file-upload urlconnection

Curretly,我可以在终端(MAC)中使用此命令上传.wav文件:

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

我想在Android上做同样的事情。到目前为止,我已经实现了一个带有URLConnection的AsyncTask,我发送了标题和除wave文件之外的所有内容。得到一个json响应,告诉没有文件被上传,显然,但到目前为止,我知道我正确实现了标头和连接。 现在,我想上传.wav文件来包装所有内容,但我在这里有点迷失。 如何使用URLConnection上传Android中的.wav文件?下面是我的代码,它是在AsyncTask里面,我不会把它放在一边简短:

         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;
                    }

2 个答案:

答案 0 :(得分:2)

我终于找到了上传wav文件的方法。某些服务器接受或拒绝上传请求的方式略有不同。在另一个问题URLConnection always returns 400 : Bad Request when I try to upload a .wav file我试图在不同的服务器上完成同样的任务,并且证明比我在这个答案中要分享的更复杂,但如果你仍然不能看看它使事情有效。 没有简单的方法直接将CURL请求“翻译”到java而不会弄乱NDK。 对于这个问题,这是适合我的代码:

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 = "\r\n"; // 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);
    }
}

答案 1 :(得分:2)

这是为wit.ai写的更简单的代码我希望它有所帮助:

String requestURL = "https://api.wit.ai/speech?v=20160526";
URL url = new URL(requestURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);

httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("Cache-Control", "no-cache");
httpConn.setRequestProperty("Authorization", "Bearer XXXXXXXXXXXXXXXXXXXXXX");;
httpConn.setRequestProperty("Content-Type", "audio/wav");;
File waveFile= new File("RecordAudio.wav");
byte[] bytes = Files.readAllBytes(waveFile.toPath());
DataOutputStream request = new DataOutputStream(httpConn.getOutputStream());
request.write(bytes);
request.flush();
request.close();

String response = "";
// checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
    InputStream responseStream = new BufferedInputStream(httpConn.getInputStream());

    BufferedReader responseStreamReader
            = new BufferedReader(new InputStreamReader(responseStream));

    String line = "";
    StringBuilder stringBuilder = new StringBuilder();

    while ((line = responseStreamReader.readLine()) != null) {
        stringBuilder.append(line).append("\n");
    }
    responseStreamReader.close();

    response = stringBuilder.toString();
    httpConn.disconnect();
} else {
    throw new IOException("Server returned non-OK status: " + status);
}