方法一:使用正则表达式
final static Pattern pattern = Pattern.compile("\\S*[?]\\S*");
/**
* 获取链接的后缀名
* @return
*/
private static String parseSuffix(String url) {
Matcher matcher = pattern.matcher(url);
String[] spUrl = url.toString().split("/");
int len = spUrl.length;
String endUrl = spUrl[len - 1];
if(matcher.find()) {
String[] spEndUrl = endUrl.split("\\?");
return spEndUrl[0].split("\\.")[1];
}
return endUrl.split("\\.")[1];
}
方法二:使用输出流
/**
* 获取链接的后缀名
* @return
*/
public static String parseSuffix(String strUrl) {
BufferedInputStream bis = null;
HttpURLConnection urlConnection = null;
URL url = null;
try {
url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
bis = new BufferedInputStream(urlConnection.getInputStream());
return HttpURLConnection.guessContentTypeFromStream(bis);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}