A Guide to the Java URL – Java URL指南

最后修改: 2016年 11月 9日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this article, we are going to explore low-level operations with Java network programming. We’ll be taking a deeper look at URLs.

在这篇文章中,我们将探讨Java网络编程的低级操作。我们将更深入地了解URLs。

A URL is a reference or an address to a resource on the network. And simply put, Java code communicating over the network can use the java.net.URL class to represent the addresses of resources.

URL是对网络上某一资源的引用或地址。简单地说,通过网络通信的Java代码可以使用java.net.URL类来表示资源的地址。

The Java platform ships with built-in networking support, bundled up in the java.net package:

Java平台有内置的网络支持,捆绑在java.net包中。

import java.net.*;

2. Creating a URL

2.创建一个URL

Let’s first create a java.net.URL object by using its constructor and passing in a String representing the human readable address of the resource:

让我们首先使用其构造函数创建一个java.net.URL对象,并传入一个代表资源的人类可读地址的字符串。

URL url = new URL("/a-guide-to-java-sockets");

We’ve just created an absolute URL object. The address has all the parts required to reach the desired resource.

我们刚刚创建了一个绝对的URL对象。该地址具有到达所需资源所需的所有部分。

We can also create a relative URL; assuming we have the URL object representing the home page of Baeldung:

我们还可以创建一个相对的URL;假设我们有代表Baeldung主页的URL对象。

URL home = new URL("http://baeldung.com");

Next, let’s create a new URL pointing to a resource we already know; we’re going to use another constructor, that takes both an existing URL and a resource name relative to that URL:

接下来,让我们创建一个新的URL,指向一个我们已经知道的资源;我们将使用另一个构造函数,它需要一个现有的URL和一个相对于该URL的资源名称。

URL url = new URL(home, "a-guide-to-java-sockets");

We have now created a new URL object url relative to home; so the relative URL is only valid within the context of the base URL.

我们现在创建了一个新的URL对象url,相对于home;所以相对URL只在基本URL的范围内有效。

We can see this in a test:

我们可以在一个测试中看到这一点。

@Test
public void givenBaseUrl_whenCreatesRelativeUrl_thenCorrect() {
    URL baseUrl = new URL("http://baeldung.com");
    URL relativeUrl = new URL(baseUrl, "a-guide-to-java-sockets");
    
    assertEquals("http://baeldung.com/a-guide-to-java-sockets", 
      relativeUrl.toString());
}

However if the relative URL is detected to be absolute in its component parts, then the baseURL is ignored:

然而,如果检测到相对URL的组成部分是绝对的,那么baseURL将被忽略。

@Test
public void givenAbsoluteUrl_whenIgnoresBaseUrl_thenCorrect() {
    URL baseUrl = new URL("http://baeldung.com");
    URL relativeUrl = new URL(
      baseUrl, "/a-guide-to-java-sockets");
    
    assertEquals("http://baeldung.com/a-guide-to-java-sockets", 
      relativeUrl.toString());
}

Finally, we can create a URL by calling another constructor which takes in the component parts of the URL string. We will cover this in the next section after covering URL components.

最后,我们可以通过调用另一个构造函数来创建一个URL,该构造函数接收URL字符串的组成部分。我们将在下一节介绍URL组件后再讨论这个问题。

3. URL Components

3.URL组件

A URL is made up of a few components – which we’ll explore in this section.

一个URL是由几个部分组成的–我们将在本节探讨。

Let’s first look at the separation between the protocol identifier and the resource – these two components are separated by a colon followed by two forward slashes i.e. ://.

让我们先看看协议标识符和资源之间的分离–这两个部分由冒号和两个正斜杠分开,即://。

If we have a URL such as http://baeldung.com then the part before the separator, http, is the protocol identifier while the one that follows is the resource name, baeldung.com.

如果我们有一个URL,如http://baeldung.com,那么分隔符之前的部分,http,是协议标识符,而后面的部分是资源名称,baeldung.com

Let’s have a look at the API that the URL object exposes.

让我们看看URL对象所暴露的API。

3.1. The Protocol

3.1.议定书》

To retrieve the protocol – we use the getProtocol() method:

为了检索协议 – 我们使用getProtocol()方法。

@Test
public void givenUrl_whenCanIdentifyProtocol_thenCorrect(){
    URL url = new URL("http://baeldung.com");
    
    assertEquals("http", url.getProtocol());
}

3.2. The Port

3.2.港口

To get the port – we use the getPort() method:

为了获得端口 – 我们使用getPort()方法。

@Test
public void givenUrl_whenGetsDefaultPort_thenCorrect(){
    URL url = new URL("http://baeldung.com");
    
    assertEquals(-1, url.getPort());
    assertEquals(80, url.getDefaultPort());
}

Note that this method retrieves the explicitly defined port. If no port is defined explicitly, it will return -1.

注意,这个方法检索的是明确定义的端口。如果没有明确定义的端口,它将返回-1。

And because HTTP communication uses port 80 by default – no port is defined.

而且由于HTTP通信默认使用80端口–没有定义端口。

Here’s an example where we do have an explicitly defined port:

下面是一个例子,我们确实有一个明确定义的端口。

@Test
public void givenUrl_whenGetsPort_thenCorrect(){
    URL url = new URL("http://baeldung.com:8090");
    
    assertEquals(8090, url.getPort());
}

3.3. The Host

3.3.主持人

The host is the part of the resource name that starts right after the :// separator and ends with the domain name extension, in our case .com.

主机是资源名称中紧随://分隔符之后开始的部分,以域名扩展名结束,在我们的例子中是.com

We call the getHost() method to retrieve the hostname:

我们调用getHost()方法来检索主机名。

@Test
public void givenUrl_whenCanGetHost_thenCorrect(){
    URL url = new URL("http://baeldung.com");
    
    assertEquals("baeldung.com", url.getHost());
}

3.4. The File Name

3.4.文件名称

Whatever follows after the hostname in a URL is referred to as the file name of the resource. It can include both path and query parameters or just a file name:

在URL中主机名之后的内容被称为资源的文件名。它可以包括路径和查询参数,也可以只是一个文件名。

@Test
public void givenUrl_whenCanGetFileName_thenCorrect1() {
    URL url = new URL("http://baeldung.com/guidelines.txt");
    
    assertEquals("/guidelines.txt", url.getFile());
}

Assuming Baeldung has java 8 articles under the URL /articles?topic=java&version=8. Everything after the hostname is the file name:

假设Baeldung在URL/articles?topic=java&version=8下有java 8文章。主机名后面的所有内容都是文件名。

@Test
public void givenUrl_whenCanGetFileName_thenCorrect2() {
    URL url = new URL("http://baeldung.com/articles?topic=java&version=8");
    
    assertEquals("/articles?topic=java&version=8", url.getFile());
}

3.5. Path Parameters

3.5.路径参数

We can also only inspect the path parameters which in our case is /articles:

我们也只能检查路径参数,在我们的例子中是/articles

@Test
public void givenUrl_whenCanGetPathParams_thenCorrect() {
    URL url = new URL("http://baeldung.com/articles?topic=java&version=8");
    
    assertEquals("/articles", url.getPath());
}

3.6. Query Parameters

3.6.查询参数

Likewise, we can inspect the query parameters which is topic=java&version=8:

同样地,我们可以检查查询参数,即topic=java&version=8

@Test
public void givenUrl_whenCanGetQueryParams_thenCorrect() {
    URL url = new URL("http://baeldung.com/articles?topic=java<em>&version=8</em>");
    
    assertEquals("topic=java<em>&version=8</em>", url.getQuery());
}

4. Creating URL With Component Parts

4.用组成部件创建URL

Since we have now looked at the different URL components and their place in forming the complete address to the resource, we can look at another method of creating a URL object by passing in the component parts.

由于我们现在已经看了不同的URL组件以及它们在形成资源的完整地址中的位置,我们可以看看通过传递组件部分来创建一个URL对象的另一种方法。

The first constructor takes the protocol, the hostname and the file name respectively:

第一个构造函数分别接受协议、主机名和文件名。

@Test
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect() {
    String protocol = "http";
    String host = "baeldung.com";
    String file = "/guidelines.txt";
    URL url = new URL(protocol, host, file);
    
    assertEquals("http://baeldung.com/guidelines.txt", url.toString());
}

Keep in mind the meaning of filename in this context, the following test should make it clearer:

牢记文件名在这里的含义,下面的测试应该更清楚。

@Test
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect2() {
    String protocol = "http";
    String host = "baeldung.com";
    String file = "/articles?topic=java&version=8";
    URL url = new URL(protocol, host, file);
    
    assertEquals("http://baeldung.com/articles?topic=java&version=8", url.toString());
}

The second constructor takes the protocol, the hostname, the port number and the filename respectively:

第二个构造函数分别接受协议、主机名、端口号和文件名。

@Test
public void givenUrlComponentsWithPort_whenConstructsCompleteUrl_
  thenCorrect() {
    String protocol = "http";
    String host = "baeldung.com";
    int port = 9000;
    String file = "/guidelines.txt";
    URL url = new URL(protocol, host, port, file);
    
    assertEquals(
      "http://baeldung.com:9000/guidelines.txt", url.toString());
}

5. Conclusion

5.结论

In this tutorial, we covered the URL class and showed how to use it in Java to access network resources programmatically.

在本教程中,我们介绍了URL类,并展示了如何在Java中使用它来以编程方式访问网络资源。

As always, the full source code for the article and all code snippets can be found in the GitHub project.

一如既往,文章的完整源代码和所有代码片段都可以在GitHub项目中找到。