How does java obtain url domain names and automatically concatenate URLs?

Source: Internet
Author: User
Tags curl

For example, a webpage is called

Http://xx.com/a2/

Parse the content of this webpage, which contains many

<A href = "/b2/"> b2 </a>
<A href = "2.html"> 2.html </a>
<A href = "../3.html"> 3.html </a>


If the calculation is performed one by one, it seems to be tolerable. java is used to determine that, for example, "/" at the beginning indicates that the root directory should be added, and "../" indicates that the root directory should be jumped up to a certain level.

What if.../appears. Jump up to Level 2

.../Jump up to 3 levels

There are some unexpected ones, such ./

There is no need to make judgments one by one. java already has built-in functions to solve the url splicing problem.

The code is as follows: Copy code
JoinUrl ("http://xx.com/a2/", "/b2 /");

Everything is done.

The code is as follows: Copy code
Public static String joinUrl (String curl, String file ){
URL url = null;
String q = "";
Try {
Url = new URL (curl), file );
Q = url. toExternalForm ();
} Catch (MalformedURLException e ){
 
  }
Url = null;
If (q. indexOf ("#")! =-1) q = q. replaceAll ("^ (. + ?) #.*? $ "," $1 ");
Return q;
 }

 
Used to quickly obtain domain names

The code is as follows: Copy code

Public static String getDomain (String curl ){
URL url = null;
String q = "";
Try {
Url = new URL (curl );
Q = url. getHost ();
} Catch (MalformedURLException e ){
 
  }
Url = null;
Return q;
 }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.