2
我有一個應用程序,它在正常情況下從雲存儲中加載和播放音樂沒有問題,除非涉及到Dropbox簡短鏈接。 這些鏈接使用302頭重定向到HTTPS鏈路: -302在Android中使用Dropbox將http重定向到https超鏈接
302實測值的資源被發現在 https://www.dropbox.com/s/jhzh3woy3qxblck/05%20-%20Cinema.ogg;你應該自動重定向你的 。
此代碼的結構是一個雙靜態方法,首先[按時間順序]查找重定向,第二個將數據獲取到文件。
我試圖讓它工作,因爲第二個鏈接當前使我從Dropbox下載了大量不相關的HTML,而不是所需的文件本身!
/**
* Return an Audio File from a URL String
* throws IOException
*
* @param url the URL which provides the target
* @return File - audio file
*/
public static File getAudioFile(String urlString, File f) {
String newUrl = null;
try {
newUrl = getRedirect(urlString);
} catch (ClientProtocolException e) {
Log.e(TAG, "ClientProtocolException Error getting Redirect ", e);
} catch (IOException e) {
Log.e(TAG, "IOException Error getting Redirect", e);
}
if (newUrl != null) {
urlString = newUrl;
}
else {
Log.i(TAG, "IOException Error getting Redirect because its null");
}
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(true);
conn.setReadTimeout(40 * 1000);
conn.setConnectTimeout(45 * 1000);
conn.setRequestMethod("GET");
conn.setRequestProperty("Connection", "close");
conn.setDoInput(true);
conn.setDefaultUseCaches(true);
// Starts the input from the URL
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
BufferedOutputStream bof = new BufferedOutputStream(new FileOutputStream(f));
// write the inputStream to the FileOutputStream
byte [] bytes = new byte [409600];
int block;
while((block = bis.read(bytes, 0, bytes.length)) > 0) {
bof.write(bytes, 0, block);
Log.d(TAG, "Write a block of " + block);
}
bof.flush();
bof.close();
bis.close();
is.close();
conn.disconnect();
} catch (Exception e) {
Log.e(TAG, "Error getting Audio File", e);
}
return f;
}
/**
* Get the new url from a http redirect
* throws IOException
*
* @param url the URL which provides the target
* @return url - the single url redirect
*/
public static String getRedirect(String urlString) throws ClientProtocolException, IOException {
HttpParams httpParameters = new BasicHttpParams();
HttpClientParams.setRedirecting(httpParameters, false);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpGet httpget = new HttpGet(urlString);
HttpContext context = new BasicHttpContext();
HttpResponse response = httpClient.execute(httpget, context);
// If we didn't get a '302 Found' we aren't being redirected.
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY)
throw new IOException(response.getStatusLine().toString());
Header loc[] = response.getHeaders("Location");
return loc.length > 0 ? loc[loc.length -1].getValue() : null;
}
我獨自這個問題了一會兒。最終看起來,一些簡短的超鏈接[在我的案例中的Dropbox音頻]實際上重定向到HTML下載屏幕。 這是沒用的什麼鏈接應該做恕我直言。 – loser114491