Simple way to convert a URL into a filename - android

I'm writing an asynchronous image downloader for Android and was just wondering, given an arbitary URL such as:
http://www.android.com/images/brand/droid.gif
What would be the best way to convert the unique url to a filename. I thought about simply splitting the url and grabbing the last section, but I want the filename to be representative of the whole URL. The other alternatives I thought were replacing all the forward slashes with underscores or simply hashing the whole URL and storing this.
If anyone has any ideas I'd love to hear them!
Thanks

In case, usually uses MD5 hash. but I suggest to use 'aquery' library. In library you can simply download Image asynchronous and put it to view. It also support disk cache, memory cache simply.

This method will be fulfill your requirements. It will generate a name which will represent original URL. You can call generateNameFromUrl(String url) method like this.
String url = "http://www.android.com/images/brand/droid.gif";
String uniqueName = generateNameFromUrl(url));
Method is given below:
public static String generateNameFromUrl(String url){
// Replace useless chareacters with UNDERSCORE
String uniqueName = url.replace("://", "_").replace(".", "_").replace("/", "_");
// Replace last UNDERSCORE with a DOT
uniqueName = uniqueName.substring(0,uniqueName.lastIndexOf('_'))
+"."+uniqueName.substring(uniqueName.lastIndexOf('_')+1,uniqueName.length());
return uniqueName;
}
Input: "http://www.android.com/images/brand/droid.gif"
Output: "http_www_android_com_images_brand_droid.gif"

Related

Convert string to a valid URL link

I am parsing some values from a website with JSoup, some of them are also url links (href).
When I get the url link, which I set to a string. The string sometimes does not become a valid URL link as it has a special character like '!?()
Example: https://somelink.com/King's+Beak (The ' makes the link not valid).
Now I tackle this by replacing the characters with the default character set for UTF-8, which works as it should.
Example code:
String test = arTD.select("a.wiki_link").get(0).attr("href").replaceAll("'", "%27");
I also set JSoup to UTF-8 but that does not seem to work.
Document document = Jsoup.parse(response.body().string(), "UTF-8");
Now my question is, is there a more convenient way to tackle this?, as I need to escape more characters like '!?().
Thank you in advance.
One way to solve this issue is to use the URLEncoder.encode() method to encode the URL string. This method will replace special characters with their corresponding ASCII codes.
String test = arTD.select("a.wiki_link").get(0).attr("href");
String encodedUrl = URLEncoder.encode(test, StandardCharsets.UTF_8);
Another way to solve this issue is by using the Uri.Builder class in android to encode the URL.
Uri.Builder builder = new Uri.Builder()
.scheme("https")
.authority("link.com")
.appendPath("King's+Beak");
Uri uri = builder.build();
String encodedUrl = uri.toString();
The first method will encode the whole url while the second method will only encode the path of the url.
Choose the suitable one for you.

Android: Create correct file name from url

I download file from many URLs.
e.g.:
https://myhost/sh/8n0wli4v5895jom/AAB2E0WA2fetPTLjWtYe5HjAa/00019.jpg
https://myhost/sh/8n0wli4v5895jom/AAB2E0WA2fetPTLjWtYe5HjAa/0001.jpg
https://myhost2222/sh/8n0wli4v5895jom/AAB2E0WA2fetPTLjWtYe5HjAa/00019.jpg
https://myhost2222/sh/8n0wli4v5895jom/AAB2E0WA2fetPTLjWtYe5HjAa/0001.jpg
Now I need to save all download files to Android local folder.
But what is file name must be?
I think to create file name from URL.
But URL contain forbidden characters for file name. So... I thing to create hash (SHA-1) from url or maybe convert URL to Base64.
Is this a good solution?
The idea is to save the file with filename the same as the URL it was downloaded from. This way it will be easy to find it (reconstruct the filename) in the filesystem (cache) given the URL.
So suppose we have this URL: https://myhost/sh/8n0wli4v5895jom/AAB2E0WA2fetPTLjWtYe5HjAa/00019.jpg
Invalid characters are : and /, so a simple String.replaceAll will remove these characters
String filename = "https://myhost/sh/8n0wli4v5895jom/AAB2E0WA2fetPTLjWtYe5HjAa/00019.jpg".replaceAll(":\\/\\/|\\/", "");
This filename variable equals to: httpsmyhostsh8n0wli4v5895jomAAB2E0WA2fetPTLjWtYe5HjAa00019.jpg
Of course if you want you can instead of completely removing those characters, to replace them with a valid character e.g. -.
make names from time:
String carTime = String.valueOf(System.currentTimeMillis());
String fileName=carTime.substring(carTime.length() - 4, carTime.length())+".jpg"
I think a base64 is good solution if you want a reversed way.
URL => FILENAME (encode base64)
FILENAME => URL (decode base64)
If you just replace : and \ by nothing you lose information and can't
retreive the orginal URL from FILENAME
If you use a Hash fonction you lose information too (and you add a very very very small risk of collision)
Maybe today you don't need a reversed solution but tomorrow for debug you don't know ;-)
Be carrefull : Filenames have limit length
EDIT :
Another solution is to simply create intermediate directory (replacing only https:// by your local temp folder)

IllegalArgumentException IN ANDROID URL

Using the below url I got an error:
java.lang.IllegalArgumentException: Illegal character in path at index 47: http://safetracker-threetinker.rhcloud.com/api/{userid}/locations?lat={latitude}&lng={longitude}.
URL:
URL=http://safetracker-threetinker.rhcloud.com/api/{userid}/locations?lat={latitude}&lng={longitude}
how to solve the error. I don't have good knowledge in URL encoding. please help me to find the solution.
The problem is actually it is looking for long/integer value and you are passing a { just put a $ so that it will be replaced by the actual value pointed by the variable
http://safetracker-threetinker.rhcloud.com/api/1/locations?lat=5&lng=5
your Address is like this
URL=http://safetracker-threetinker.rhcloud.com/api/{userid}/locations?lat={latitude}&lng={longitude}
it should be like this
URL=http://safetracker-threetinker.rhcloud.com/api/${userid}/locations?lat=${latitude}&lng={longitude}
We can not use some special characters in URL, so we have to replace these special characters with its encoded form.
Replace your URL with following URL
URL=http://safetracker-threetinker.rhcloud.com/api/%7Buserid%7D/locations?lat=%7Blatitude%7D&lng=%7Blongitude%7D
May this help you.
URLEncoder should be the way to go. You only need to keep in mind to encode only the individual query string parameter name and/or value, not the entire URL, for sure not the query string parameter separator character & nor the parameter name-value separator character =.
String q = "replace_with user_id/locations?lat=replace with latitude&lng=replace with longitude";
String url = "http://safetracker-threetinker.rhcloud.com/api/=" + URLEncoder.encode(q, "UTF-8");

Trouble Removing Whitespace in URL (Android Studio)

So I have a for loop that retrieves a room name to add to my baseurl, and so my URL will be this:
a = (baseUrl + roomName + "/users");
It works for all the rooms except one, which has a space, so I tried using this:
a.replaceAll("\\s+", "");
and other attemps but they return this
System.err﹕ java.io.FileNotFoundException: https://example.com:8443/conferenceRoom/First Floor/users
System.err﹕ at http.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)
Basically, I have a link like https://example.com:8443/conferenceRoom/First Floor/users
and I want it to be https://example.com:8443/conferenceRoom/FirstFloor/users so no space between 'first' and 'floor'
(note I do use openURLConnection(a) ) when actually using the URL later but I don't think it has anything to pertain to my problem, just wanted to clarify that a is a string
If you want to remove whitespaces from your url you can use trim() as
a= a.trim();
If you want to replace whitespaces with "%20" then you can use
a = a.replace(" ", "%20");
Having spaces in URLs can cause problems in certain situations. Therefore, a lot of the time spaces are replaced with %20 (which is the ascii encoded value for a space in a URL string). If you remove spaces from your URLs, you won't have the %20s. Otherwise, they're going to stick around.
Your url might contain UTF whitespaces which are not covered by the \s mofidier.
Just use trim which removes all whitespaces:
a = a.trim();

extracting strings from KML file

I am extracting strings from KML file, if the string contains special character like !, #, #, ', " etc. its using codes like '
I am not able to extract entire string if it is like above, by calling getNodeValue(). It is terminating the string at special character.
<name>Continue onto Royal's Market</name>
If i extract the string i am getting only ""Continue onto Royal". I want entire string as
Continue onto Royal's Market.
How to achieve this ?? If anybody familiar with this please reply to this one.
Thanks
Your problem has nothing to do with KML but is general for XML parsning:
Don't use getNodeValue(), as there is no guarantee in DOM that text isn't actually split over several nodes.
Try using getTextContent() instead.
You might also have to replace entities, as in: node.getTextContent().replaceAll("'","'");
In general I wouldnt use DOM at all for extracting data.
I'd use the XmlPullParser as its simpler to work with - and parses faster.

Categories

Resources