URLConnection retourne toujours 400: mauvaise requête quand j'essaie de télécharger un.fichier wav
je veux implémenter un code qui fait exactement ce que j'accomplis quand j'exécute une commande CURL dans le terminal de mon Mac, qui est de télécharger un .fichier wav vers un serveur. J'ai déjà fait cela pour un serveur auparavant, donc ma pensée générale fonctionne (et mon code aussi), ....mais maintenant, je veux accomplir la même chose mais sur un autre serveur. Cette fois j'ai des problèmes et tout ce que j'obtiens sont "400: Bad Request "
c'est la commande CURL que je veux faire sur Android, j'ai j'ai ajouté un "- v " pour que vous puissiez voir le verbose de ma commande.
curl -F file=@audio_life.wav 11.2.333.44:14141/transcribe -v
journal de sortie dans le Terminal:
* Trying 11.2.333.44...
* Connected to 11.2.333.44 (11.2.333.44) port 14141 (#0)
> POST /transcribe HTTP/1.1
> Host: 11.2.333.44:14141
> User-Agent: curl/7.43.0
> Accept: */*
> Content-Length: 304898
> Expect: 100-continue
> Content-Type: multipart/form-data; boundary=------------------------62142b52672c69e0
>
* Done waiting for 100-continue
< HTTP/1.1 201 Created
< Content-Type: application/json
< Content-Length: 915
C'est mon code, j'obtiens toujours 400:Bad Request responses, comme vous pouvez le voir j'ai essayé de répliquer les en-têtes. Ce que je fais mal? Comment puis-je conclure sur ce que peut être l'erreur?
String wavpath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/ArtificialSolutions/"+StorageUtils.AUDIO_FILE_NAME+".wav";
File wavfile = new File(wavpath);
FileInputStream fileInputStream = new FileInputStream(wavpath);
connectURL = new URL(ASR_URL_VOCITEC);
String filevalue = StorageUtils.AUDIO_FILE_NAME+".wav";
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Host","11.2.333.44:14141");
conn.setRequestProperty("User-Agent", "android");
conn.setRequestProperty("Accept","*/*");
conn.setRequestProperty("Transfer-Encoding", "chunked");
conn.setRequestProperty("Expect", "100-continue");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=------------------------f016e997e308ec07");//+boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name="File""+ lineEnd);
//dos.writeBytes("Content-Disposition: form-data; File=""+wavpath+"""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(wavpath);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[ ] buffer = new byte[bufferSize];
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0){
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
Log.e("joshtag","BytesAvailable: "+bytesAvailable);
bufferSize = Math.min(bytesAvailable,maxBufferSize);
if(bytesAvailable>maxBufferSize){
bytesRead = fileInputStream.read(buffer, 0,bufferSize);
}
else{
bytesRead = fileInputStream.read(buffer, 0,bytesAvailable);
dos.write(buffer, 0, bytesAvailable);
break;
}
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
fileInputStream.close();//63532 , 64556
dos.flush();
Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));
Log.e(Tag,"File Sent, ResponseMSG: "+String.valueOf(conn.getResponseMessage()));
ceci est une impression du message que je reçois du serveur:
{null=[HTTP/1.1 400 Bad Request], Content-Length=[42], Content-Type=[text/plain], X-Android-Received-Millis=[1449836192887], X-Android-Response-Source=[NETWORK 400], X-Android-Sent-Millis=[1449836192719]}
NOTE: I codé cela basé sur le meilleur de ma connaissance et après avoir examiné les messages liés ici sur StartOverflow, le code entier est à l'intérieur de la méthode de doInBackground D'un AsyncTask donc permet de se concentrer ici. J'espère pourront m'aider!! Grâce.
1 réponses
après avoir beaucoup trafiqué le code, j'ai trouvé un moyen de télécharger un fichier wav avec URLConnection, et en utilisant multipartentity. Voici le code, enjoy:
public int uploadWav(String sourceFileUri) {
String wavpath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/myAppFolder/"+StorageUtils.AUDIO_FILE_NAME+".wav";
String filename=wavpath;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "------------------------afb19f4aeefb356c";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(fileName);
Log.e("joshtag", "Uploading: sourcefileURI, "+fileName);
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File not exist :"+wavpath);//FullPath);
return 0; //RETURN #1
}
else{
try{
Log.v("joshtag","UPLOADING .WAV FILE");
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(SERVER_URL);
Log.v("joshtag","UL URL: "+url.toString());
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy s
conn.setRequestMethod("POST");
// conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("file", sourceFile.getName());
//so on and so forth...
//conn.setRequestProperty("param", "value");
conn.setRequestProperty("connection", "close");
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + sourceFile.getName() + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
Log.i("joshtag","->");
}
Log.i("joshtag","->->");
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
conn.connect();
Log.i("joshtag","->->->");
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
Log.i("joshtag","->->->->");
String serverResponseMessage = conn.getResponseMessage().toString();
Log.i("joshtag","->->->->->");
Log.i("joshtag", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
// ------------------ read the SERVER RESPONSE
DataInputStream inStream;
String str="";
String response="";
try {
Log.i("joshtag","->->->->->->");
inStream = new DataInputStream(conn.getInputStream());
while ((str = inStream.readLine()) != null) {
Log.e("joshtag", "SOF Server Response" + str);
response=str;
}
inStream.close();
}
catch (IOException ioex) {
Log.e("joshtag", "SOF error: " + ioex.getMessage(), ioex);
}
conn.disconnect();
conn=null;
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
if(serverResponseCode == 201){
loge("*** SERVER RESPONSE: 201"+response);
}//END IF Response code 201
// conn.disconnect();
}//END TRY - FILE READ
catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("joshtag", "UL error: " + ex.getMessage(), ex);
} //CATCH - URL Exception
catch (Exception e) {
e.printStackTrace();
Log.e("Upload file to server Exception", "Exception : "+ e.getMessage(), e);
}
return serverResponseCode; //after try
}//END ELSE, if file exists.
}