开发者

How can I represent URL (possibly including query string) as a filename in Java without obscuring the original URL?

开发者 https://www.devze.com 2023-02-04 04:28 出处:网络
Is there any real way to represent a URL (which more than likely will also have a query string) as a filename in Java without obscuring the original URL completely?

Is there any real way to represent a URL (which more than likely will also have a query string) as a filename in Java without obscuring the original URL completely?

My first approach was to simply escape invalid characters with arbitrary replacements (for example, replacing "/" with "_", etc). The problem is, as in the example of replacing with underscores is that a URL such as "app/my_app" would become "app_my_app" thus obscuring the original URL completely. I have also attempted to encode all th开发者_运维知识库e special characters, however again, seeing crazy %3e %20 etc is really not clear.

Thank you for any suggestions.


Well, you should know what you want here, exactly. Keep in mind that the restrictions on file names vary between systems. On a Unix system you probably only need to escape the virgule somehow, whereas on Windows you need to take care of the colon and the question mark as well.

I guess, the safest thing would be to encode anything that could potentially clash (everything non-alphanumeric would be a good candidate, although you migth adapt this to the platform) with percent-encoding. It's still somewhat readable and you're guaranteed to get the original URL back.


Why? URL-encoding is already defined in an RFC: there's not much point in reinventing it. Basically you must have an escape character such as %, otherwise you can't tell whether a character represents itself or an escape. E.g. in your example app_my_app could represent app/my/app. You therefore also need a double-escape convention so you can represent the escape character itself. It is not simple.

0

精彩评论

暂无评论...
验证码 换一张
取 消