当我使用Android将视频上传到服务器(Vimeo)时,一切正常。
但是在上传期间,如果我失去网络连接,则无法触发DataOutputStream的.write I / O异常。 所以我的应用程序冻结了。
如何触发异常以恢复或重置我的上传?
我的try / catch不会触发异常…
这是我的代码:
private void call_for_ticket(String upload_url, String complet_uri, String videoUri) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(videoUri);
if (sourceFile.isFile())
{
try
{
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upload_url);
// 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
conn.setRequestMethod("PUT");
conn.setRequestProperty("Authorization",Aurtorizartion);
conn.setRequestProperty("Accept",accept);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "video/mp4");
conn.setChunkedStreamingMode(-1);
try {
dos = new DataOutputStream(conn.getOutputStream());
// 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);
long bytesAvailableReadIncrementation = 0;
long totalFileSize = bytesAvailable;
try{
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math
.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0,
bufferSize);
bytesAvailableReadIncrementation += bytesRead;
publishProgress("" + (long) ((bytesAvailableReadIncrementation * 100) / totalFileSize));
}
} catch (IOException e) {
Log.d("VMA", "lost connection");
e.printStackTrace();
}
// send multipart form data necesssary after file
// data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
int serverResponseCode;
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn
.getResponseMessage();
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
if (serverResponseCode == 200) {
call_complete_uri(complet_uri);
}
}
catch (IOException e)
{
Log.d("VMA", "lost connection");
e.printStackTrace();
}
} catch (IOException e) {
Log.d("VMA", "lost connection");
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
好吧,我知道了。
我正在模拟器上测试代码。 在实际设备上,会引发异常:)。