Android 检测 URL MIME 类型
在 Android 应用中,常常需要处理不同的 MIME 类型数据,例如图片、音频、视频等。在 Android 中,可以使用 URLConnection
或 HttpUrlConnection
类来检测 URL 的 MIME 类型。以下是一个简单的示例代码:
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class UrlMimeDetector {
private static final String TAG = "UrlMimeDetector";
private static final String DEFAULT_MIME_TYPE = "application/octet-stream";
private String mimeType = DEFAULT_MIME_TYPE;
public UrlMimeDetector() {
}
public String getMimeType(String url) {
if (!url.startsWith("http")) {
return DEFAULT_MIME_TYPE;
}
Uri uri = Uri.parse(url);
String path = uri.getPath();
if (path == null) {
path = "";
}
String extension = getExtension(path);
if (extension == null) {
return DEFAULT_MIME_TYPE;
}
mimeType = getMimeTypeFromExtension(extension);
if (mimeType == null) {
return DEFAULT_MIME_TYPE;
}
return mimeType;
}
private String getExtension(String path) {
if (path.length() == 0) {
return null;
}
int dotIndex = path.lastIndexOf(".");
if (dotIndex == -1) {
return null;
}
return path.substring(dotIndex + 1);
}
private String getMimeTypeFromExtension(String extension) {
if (extension == null) {
return null;
}
if (extension.equals("pdf")) {
return "application/pdf";
} else if (extension.equals("png")) {
return "image/png";
} else if (extension.equals("jpg") || extension.equals("jpeg")) {
return "image/jpeg";
} else if (extension.equals("gif")) {
return "image/gif";
} else if (extension.equals("bmp")) {
return "image/bmp";
} else if (extension.equals("txt")) {
return "text/plain";
} else if (extension.equals("json")) {
return "application/json";
} else if (extension.equals("xml")) {
return "text/xml";
} else if (extension.equals("zip")) {
return "application/zip";
} else if (extension.equals("7z")) {
return "application/x-7z-compressed";
} else if (extension.equals("flv")) {
return "video/x-flv";
} else if (extension.equals("mp4")) {
return "video/mp4";
} else if (extension.equals("mov")) {
return "video/quicktime";
} else if (extension.equals("avi")) {
return "video/x-msvideo";
} else if (extension.equals("wmv")) {
return "video/x-ms-wmv";
} else if (extension.equals("html")) {
return "text/html";
} else if (extension.equals("css")) {
return "text/css";
} else if (extension.equals("js")) {
return "application/javascript";
} else if (extension.equals("json")) {
return "application/json";
} else if (extension.equals("pdf")) {
return "application/pdf";
} else if (extension.equals("txt")) {
return "text/plain";
} else if (extension.equals("xml")) {
return "text/xml";
} else if (extension.equals("svg")) {
return "image/svg+xml";
} else if (extension.equals("ttf")) {
return "application/x-font-ttf";
} else if (extension.equals("
领取专属 10元无门槛券
手把手带您无忧上云