Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

java - Create URL from a String

It is a very basic question. But i am unable to find an answer in Java documentation and unable to test it as well since i don't know if such method exist or not.

I might receive a URL String which could be

http://www.example1.com

or

http://www.example1.com/

and then i will get resource path which might start with /api/v1/status.xml or it would be like api/v1/status.xml

I was looking at URL class and I can handle the first part i.e. fetching the hostURL to make it an HTTPS or HTTP request. The problem is appending the resource path. either i have to check it manually if the first letter is / or not. I was wondering if this functionality is already in some class or not.

question from:https://stackoverflow.com/questions/12730685/create-url-from-a-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
URL url = new URL(yourUrl, "/api/v1/status.xml");

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");

Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...