下面列出了android.webkit.URLUtil#isNetworkUrl ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 获取多个图片,并在全部完成的时候回调
*
* @param context
* @param urls
* @param callback
*/
public static void fetch(Context context, LuaResourceFinder finder, String[] urls, final LoadCallback callback) {
if (context != null && urls != null && urls.length > 0) {
final AtomicInteger count = new AtomicInteger(urls.length);
final Map<String, Drawable> result = new HashMap<String, Drawable>();
for ( final String url : urls) {
if (URLUtil.isNetworkUrl(url)) {//network
ImageProvider imageProvider = LuaView.getImageProvider();
if (imageProvider != null) {
imageProvider.preload(context, url, new DrawableLoadCallback() {
@Override
public void onLoadResult(Drawable drawable) {
result.put(url, drawable);
callCallback(count, callback, result);
}
});
}
} else {//TODO 优化成异步
if (finder != null) {
result.put(url, finder.findDrawable(url));
callCallback(count, callback, result);
}
}
}
}
}
public static boolean isValidSearchQueryUrl(String url) {
String trimmedUrl = url.trim();
if (!trimmedUrl.matches("^.+?://.+?")) {
// UI hint url doesn't have http scheme, so add it if necessary
trimmedUrl = "http://" + trimmedUrl;
}
if (!URLUtil.isNetworkUrl(trimmedUrl)) {
return false;
}
if (!trimmedUrl.matches(".*%s$")) {
return false;
}
return true;
}
/**
* Creates the Uri string with embedded expansion codes.
*
* @param uri to be encoded
* @return the Uri string with expansion codes.
*/
public static byte[] encodeUri(String uri) {
if (uri.length() == 0) {
return new byte[0];
}
ByteBuffer bb = ByteBuffer.allocate(uri.length());
// UUIDs are ordered as byte array, which means most significant first
bb.order(ByteOrder.BIG_ENDIAN);
int position = 0;
// Add the byte code for the scheme or return null if none
Byte schemeCode = encodeUriScheme(uri);
if (schemeCode == null) {
return null;
}
String scheme = URI_SCHEMES.get(schemeCode);
bb.put(schemeCode);
position += scheme.length();
if (URLUtil.isNetworkUrl(scheme)) {
return encodeUrl(uri, position, bb);
} else if ("urn:uuid:".equals(scheme)) {
return encodeUrnUuid(uri, position, bb);
}
return null;
}
private static String decodeUri(byte[] serviceData, int offset) {
if (serviceData.length == offset) {
return NO_URI;
}
StringBuilder uriBuilder = new StringBuilder();
if (offset < serviceData.length) {
byte b = serviceData[offset++];
String scheme = URI_SCHEMES.get(b);
if (scheme != null) {
uriBuilder.append(scheme);
if (URLUtil.isNetworkUrl(scheme)) {
return decodeUrl(serviceData, offset, uriBuilder);
} else if ("urn:uuid:".equals(scheme)) {
return decodeUrnUuid(serviceData, offset, uriBuilder);
}
}
Log.w(TAG, "decodeUri unknown Uri scheme code=" + b);
}
return null;
}
/**
* Creates the Uri string with embedded expansion codes.
*
* @param uri to be encoded
* @return the Uri string with expansion codes.
*/
public static byte[] encodeUri(String uri) {
if (uri.length() == 0) {
return new byte[0];
}
ByteBuffer bb = ByteBuffer.allocate(uri.length());
// UUIDs are ordered as byte array, which means most significant first
bb.order(ByteOrder.BIG_ENDIAN);
int position = 0;
// Add the byte code for the scheme or return null if none
Byte schemeCode = encodeUriScheme(uri);
if (schemeCode == null) {
return null;
}
String scheme = URI_SCHEMES.get(schemeCode);
bb.put(schemeCode);
position += scheme.length();
if (URLUtil.isNetworkUrl(scheme)) {
return encodeUrl(uri, position, bb);
} else if ("urn:uuid:".equals(scheme)) {
return encodeUrnUuid(uri, position, bb);
}
return null;
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
if (URLUtil.isNetworkUrl(url))
{
final Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
if (getActivity().getPackageManager().resolveActivity(i, 0) != null)
startActivity(i);
return true;
}
else if (url.startsWith("mapswithme://"))
{
final PendingIntent pi = ArticleInfoListActivity.createPendingIntent(getActivity());
// TODO: Decided to use 11 as default scale, but MapsWithMe has bug with scales,
// so do pass 13 as a compromise.
MapsWithMeApi.showMapsWithMeUrl(getActivity(), pi, 13, url);
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
/**
* Gets URL parameter from JSON and validates it.
*
* @param jsonElement - JsonElement that contains the url string.
* @param messageType - Message type.
* @return - Returns the verified URI string. If not valid or empty will return an empty string.
*/
public static String getUriFromJson(JsonElement jsonElement, int messageType) {
String urlToCheck = jsonElement == null || jsonElement.isJsonNull() ? "" : jsonElement.getAsString();
String returnUrl = "";
//we allow deep links for in app actions and URL messages; we enforce valid network URLs
// for the visit website action
if ((messageType == ServerType.IN_APP && validatedUrl(urlToCheck))
|| (messageType == ServerType.URL_MESSAGE && validatedUrl(urlToCheck))
|| URLUtil.isNetworkUrl(urlToCheck)) {
returnUrl = urlToCheck;
}
if (returnUrl.isEmpty()) {
Logger.log.logError("URL is invalid, please change in the campaign settings.");
}
return returnUrl;
}
public LuaViewCore load(String urlOrFileOrScript, String sha256, LuaScriptLoader.ScriptExecuteCallback callback) {
if (!TextUtils.isEmpty(urlOrFileOrScript)) {
if (URLUtil.isNetworkUrl(urlOrFileOrScript)) {//url, http:// or https://
loadUrl(urlOrFileOrScript, sha256, callback);
} else {
loadFile(urlOrFileOrScript, callback);
}
//TODO other schema
} else if (callback != null) {
callback.onScriptExecuted(null, false);
}
return this;
}
/**
* 获取一个图片,并调用回调
*
* @param context
* @param url
* @param callback
*/
public static void fetch(Context context, LuaResourceFinder finder, String url, DrawableLoadCallback callback) {
if (context != null && !TextUtils.isEmpty(url)) {
if (URLUtil.isNetworkUrl(url)) {//network
ImageProvider provider = LuaView.getImageProvider();
if (provider != null) {
provider.preload(context, url, callback);
}
} else {//local
if (callback != null && finder != null) {
callback.onLoadResult(finder.findDrawable(url));
}
}
}
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (URLUtil.isNetworkUrl(url)) {
if (mPresenter.isUseSystemBrowser()) {
NavigationUtil.openInBrowser(getActivity(), url);
} else {
((SupportActivity) getContext()).findFragment(MainFragment.class)
.start(WebViewFragment.newInstance(url, ""));
}
}
return true;
}
static String decodeUrl(byte[] serviceData) {
StringBuilder url = new StringBuilder();
int offset = 2;
byte b = serviceData[offset++];
String scheme = URI_SCHEMES.get(b);
if (scheme != null) {
url.append(scheme);
if (URLUtil.isNetworkUrl(scheme)) {
return decodeUrl(serviceData, offset, url);
} else if ("urn:uuid:".equals(scheme)) {
return decodeUrnUuid(serviceData, offset, url);
}
}
return url.toString();
}
public MdnsUrlDeviceDiscoverer(Context context) {
mState = State.STOPPED;
mResolver = new DiscoverResolver(context, MDNS_SERVICE_TYPE,
new DiscoverResolver.Listener() {
@Override
public void onServicesChanged(Map<String, MDNSDiscover.Result> services) {
for (MDNSDiscover.Result result : services.values()) {
// access the Bluetooth MAC from the TXT record
String url = result.txt.dict.get("url");
Log.d(TAG, url);
String id = TAG + result.srv.fqdn + result.srv.port;
String title = "";
String description = "";
if ("false".equals(result.txt.dict.get("public"))) {
if (result.txt.dict.containsKey("title")) {
title = result.txt.dict.get("title");
}
if (result.txt.dict.containsKey("description")) {
description = result.txt.dict.get("description");
}
reportUrlDevice(createUrlDeviceBuilder(id, url)
.setPrivate()
.setTitle(title)
.setDescription(description)
.setDeviceType(Utils.MDNS_LOCAL_DEVICE_TYPE)
.build());
} else if (URLUtil.isNetworkUrl(url)) {
reportUrlDevice(createUrlDeviceBuilder(id, url)
.setPrivate()
.setDeviceType(Utils.MDNS_PUBLIC_DEVICE_TYPE)
.build());
}
}
}
});
}
public static boolean isValidSearchQueryUrl(String url) {
String trimmedUrl = url.trim();
if (!trimmedUrl.matches("^.+?://.+?")) {
// UI hint url doesn't have http scheme, so add it if necessary
trimmedUrl = "http://" + trimmedUrl;
}
final boolean isNetworkUrl = URLUtil.isNetworkUrl(trimmedUrl);
final boolean containsToken = trimmedUrl.contains("%s");
return isNetworkUrl && containsToken;
}
/**
* Creates the Uri string with embedded expansion codes.
*
* @param uri to be encoded
* @return the Uri string with expansion codes.
*/
public static byte[] encodeUri(String uri) {
if (uri == null || uri.length() == 0) {
Log.i(TAG, "null or empty uri");
return new byte[0];
}
ByteBuffer bb = ByteBuffer.allocate(uri.length());
// UUIDs are ordered as byte array, which means most significant first
bb.order(ByteOrder.BIG_ENDIAN);
int position = 0;
// Add the byte code for the scheme or return null if none
Byte schemeCode = encodeUriScheme(uri);
if (schemeCode == null) {
Log.i(TAG, "null scheme code");
return null;
}
String scheme = URI_SCHEMES.get(schemeCode);
bb.put(schemeCode);
position += scheme.length();
if (URLUtil.isNetworkUrl(scheme)) {
Log.i(TAG, "is network URL");
return encodeUrl(uri, position, bb);
} else if ("urn:uuid:".equals(scheme)) {
Log.i(TAG, "is UUID");
return encodeUrnUuid(uri, position, bb);
}
return null;
}
private boolean validateInput() {
if(mUidInfoContainer.getVisibility() == View.VISIBLE) {
final String namespaceId = mNamespaceId.getText().toString().trim();
if (namespaceId.isEmpty()) {
mNamespaceId.setError("Please enter namespace id");
return false;
} else {
if (!namespaceId.matches(PATTERN_NAMESPACE_ID)) {
mNamespaceId.setError("Please enter a valid value for namespace id");
return false;
}
}
final String instanceId = mInstanceId.getText().toString().trim();
if (instanceId.isEmpty()) {
mInstanceId.setError("Please enter instance id");
return false;
} else {
if (!instanceId.matches(PATTERN_INSTANCE_ID)) {
mInstanceId.setError("Please enter a valid value for instance id");
return false;
}
}
}
if(mUrlInfoContainer.getVisibility() == View.VISIBLE) {
if(mUrlShortenerContainer.getVisibility() == View.VISIBLE){
return true;
}
String urlText = mUrl.getText().toString().trim();
if(urlText.isEmpty()){
mUrl.setError("Please enter a value for URL");
return false;
}
urlText = validateUrlText(urlText);
mUrl.setText(urlText); //updating the ui in case the user has typed in the url wrong
final String url = mUrlTypes.getSelectedItem().toString().trim() + urlText;
if (url.isEmpty()) {
mUrl.setError("Please enter a value for URL");
return false;
} else {
if (!URLUtil.isValidUrl(url)) {
mUrl.setError("Please enter a valid value for URL");
return false;
} else if (!URLUtil.isNetworkUrl(url)) {
mUrl.setError("Please enter a valid value for URL");
return false;
} else if (ParserUtils.encodeUri(url).length > 18){
mUrl.setError("Please enter a shortened URL or press use the URL shortener!");
return false;
}
}
}
if(mEidInfoContainer.getVisibility() == View.VISIBLE) {
final String timerExponent = mTimerExponent.getText().toString().trim();
if(timerExponent.isEmpty()){
mTimerExponent.setError(getString(R.string.timer_exponent_error));
return false;
} else {
boolean valid;
int i = 0;
try {
i = Integer.parseInt(timerExponent);
valid = ((i & 0xFFFFFF00) == 0 || (i & 0xFFFFFF00) == 0xFFFFFF00);
} catch (NumberFormatException e) {
valid = false;
}
if (!valid) {
mTimerExponent.setError(getString(R.string.uint8_error));
return false;
} else if ((i < 10 || i > 15)){
mTimerExponent.setError(getString(R.string.timer_exponent_error_value));
return false;
}
}
}
return true;
}
private boolean isUrlValid(String url) {
return URLUtil.isNetworkUrl(url);
}
private boolean isPreferredVideoInfo(@Nullable VideoInfo videoInfo) {
return videoInfo != null &&
URLUtil.isNetworkUrl(videoInfo.url) &&
VideoUtil.isValidVideoUrl(videoInfo.url);
}
@Nullable
public VideoInfo getYoutubeVideoInfo() {
if (youtube != null && URLUtil.isNetworkUrl(youtube.url))
return youtube;
return null;
}
private boolean isUrlValid(String url) {
return URLUtil.isNetworkUrl(url);
}
/**
* The real guts of parseNetworkResponse. Broken out for readability.
*/
private Response<Bitmap> doParse(NetworkResponse response) {
Bitmap bitmap = null;
if (URLUtil.isNetworkUrl(getUrl())) {
byte[] data = response.data;
bitmap = BitmapDecoder.bytes2Bitmap(data, mDecodeConfig, mMaxWidth, mMaxHeight);
} else {
InputStream is = BitmapDecoder.getInputStream(mContext, getUrl());
bitmap = BitmapDecoder.inputStream2Bitmap(mContext, getUrl(),is, mDecodeConfig, mMaxWidth, mMaxHeight);
}
// BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
// Bitmap bitmap = null;
// if (mMaxWidth == 0 && mMaxHeight == 0) {
// decodeOptions.inPreferredConfig = mDecodeConfig;
// bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
// } else {
// // If we have to resize this image, first get the natural bounds.
// decodeOptions.inJustDecodeBounds = true;
// BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
// int actualWidth = decodeOptions.outWidth;
// int actualHeight = decodeOptions.outHeight;
//
// // Then compute the dimensions we would ideally like to decode to.
// int desiredWidth = getResizedDimension(mMaxWidth, mMaxHeight,
// actualWidth, actualHeight);
// int desiredHeight = getResizedDimension(mMaxHeight, mMaxWidth,
// actualHeight, actualWidth);
//
// // Decode to the nearest power of two scaling factor.
// decodeOptions.inJustDecodeBounds = false;
// // TODO(ficus): Do we need this or is it okay since API 8 doesn't support it?
// // decodeOptions.inPreferQualityOverSpeed = PREFER_QUALITY_OVER_SPEED;
// decodeOptions.inSampleSize =
// findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight);
// Bitmap tempBitmap =
// BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
//
// // If necessary, scale down to the maximal acceptable size.
// if (tempBitmap != null && (tempBitmap.getWidth() > desiredWidth ||
// tempBitmap.getHeight() > desiredHeight)) {
// bitmap = Bitmap.createScaledBitmap(tempBitmap,
// desiredWidth, desiredHeight, true);
// tempBitmap.recycle();
// } else {
// bitmap = tempBitmap;
// }
// }
if (bitmap == null) {
return Response.error(new ParseError(response));
} else {
return Response.success(bitmap, HttpHeaderParser.parseCacheHeaders(response));
}
}