- Java create url parameters
- Constructor Summary
- Method Summary
- Methods inherited from class java.lang.Object
- Constructor Detail
- URL
- URL
- URL
- URL
- URL
- URL
- Method Detail
- getQuery
- Руководство по Java URL
- 2. Создание URL
- 3. Компоненты URL
- 3.1. Протокол
- 3.2. Порт
- 3.3. Гостья
- 3.4. Имя файла
- 3.5. Параметры пути
- 3.6. Параметры запроса
- 4. Создание URL с составными частями
- 5. Заключение
Java create url parameters
Class URL represents a Uniform Resource Locator, a pointer to a «resource» on the World Wide Web. A resource can be something as simple as a file or a directory, or it can be a reference to a more complicated object, such as a query to a database or to a search engine. More information on the types of URLs and their formats can be found at: Types of URL In general, a URL can be broken into several parts. Consider the following example:
http://www.example.com/docs/resource1.html
The URL above indicates that the protocol to use is http (HyperText Transfer Protocol) and that the information resides on a host machine named www.example.com . The information on that host machine is named /docs/resource1.html . The exact meaning of this name on the host machine is both protocol dependent and host dependent. The information normally resides in a file, but it could be generated on the fly. This component of the URL is called the path component. A URL can optionally specify a «port», which is the port number to which the TCP connection is made on the remote host machine. If the port is not specified, the default port for the protocol is used instead. For example, the default port for http is 80 . An alternative port could be specified as:
http://www.example.com:1080/docs/resource1.html
The syntax of URL is defined by RFC 2396: Uniform Resource Identifiers (URI): Generic Syntax, amended by RFC 2732: Format for Literal IPv6 Addresses in URLs. The Literal IPv6 address format also supports scope_ids. The syntax and usage of scope_ids is described here. A URL may have appended to it a «fragment», also known as a «ref» or a «reference». The fragment is indicated by the sharp sign character «#» followed by more characters. For example,
http://java.sun.com/index.html#chapter1
This fragment is not technically part of the URL. Rather, it indicates that after the specified resource is retrieved, the application is specifically interested in that part of the document that has the tag chapter1 attached to it. The meaning of a tag is resource specific. An application can also specify a «relative URL», which contains only enough information to reach the resource relative to another URL. Relative URLs are frequently used within HTML pages. For example, if the contents of the URL:
The relative URL need not specify all the components of a URL. If the protocol, host name, or port number is missing, the value is inherited from the fully specified URL. The file component must be specified. The optional fragment is not inherited. The URL class does not itself encode or decode any URL components according to the escaping mechanism defined in RFC2396. It is the responsibility of the caller to encode any fields, which need to be escaped prior to calling URL, and also to decode any escaped fields, that are returned from URL. Furthermore, because URL has no knowledge of URL escaping, it does not recognise equivalence between the encoded or decoded form of the same URL. For example, the two URLs:
http://foo.com/hello world/ and http://foo.com/hello%20world
would be considered not equal to each other. Note, the URI class does perform escaping of its component fields in certain circumstances. The recommended way to manage the encoding and decoding of URLs is to use URI , and to convert between these two classes using toURI() and URI.toURL() . The URLEncoder and URLDecoder classes can also be used, but only for HTML form encoding, which is not the same as the encoding scheme defined in RFC2396.
Constructor Summary
Method Summary
Returns a URLConnection instance that represents a connection to the remote object referred to by the URL .
Same as openConnection() , except that the connection will be made through the specified proxy; Protocol handlers that do not support proxing will ignore the proxy parameter and make a normal connection.
Methods inherited from class java.lang.Object
Constructor Detail
URL
public URL(String protocol, String host, int port, String file) throws MalformedURLException
- If the application has previously set up an instance of URLStreamHandlerFactory as the stream handler factory, then the createURLStreamHandler method of that instance is called with the protocol string as an argument to create the stream protocol handler.
- If no URLStreamHandlerFactory has yet been set up, or if the factory’s createURLStreamHandler method returns null , then the constructor finds the value of the system property:
If the value of that system property is not null , it is interpreted as a list of packages separated by a vertical slash character ‘ | ‘. The constructor tries to load the class named:
Protocol handlers for additional protocols may also be available. No validation of the inputs is performed by this constructor.
URL
public URL(String protocol, String host, String file) throws MalformedURLException
Creates a URL from the specified protocol name, host name, and file name. The default port for the specified protocol is used. This method is equivalent to calling the four-argument constructor with the arguments being protocol , host , -1 , and file . No validation of the inputs is performed by this constructor.
URL
public URL(String protocol, String host, int port, String file, URLStreamHandler handler) throws MalformedURLException
Creates a URL object from the specified protocol , host , port number, file , and handler . Specifying a port number of -1 indicates that the URL should use the default port for the protocol. Specifying a handler of null indicates that the URL should use a default stream handler for the protocol, as outlined for: java.net.URL#URL(java.lang.String, java.lang.String, int, java.lang.String) If the handler is not null and there is a security manager, the security manager’s checkPermission method is called with a NetPermission(«specifyStreamHandler») permission. This may result in a SecurityException. No validation of the inputs is performed by this constructor.
URL
public URL(String spec) throws MalformedURLException
Creates a URL object from the String representation. This constructor is equivalent to a call to the two-argument constructor with a null first argument.
URL
public URL(URL context, String spec) throws MalformedURLException
Creates a URL by parsing the given spec within a specified context. The new URL is created from the given context URL and the spec argument as described in RFC2396 «Uniform Resource Identifiers : Generic * Syntax» :
The reference is parsed into the scheme, authority, path, query and fragment parts. If the path component is empty and the scheme, authority, and query components are undefined, then the new URL is a reference to the current document. Otherwise, the fragment and query parts present in the spec are used in the new URL. If the scheme component is defined in the given spec and does not match the scheme of the context, then the new URL is created as an absolute URL based on the spec alone. Otherwise the scheme component is inherited from the context URL. If the authority component is present in the spec then the spec is treated as absolute and the spec authority and path will replace the context authority and path. If the authority component is absent in the spec then the authority of the new URL will be inherited from the context. If the spec’s path component begins with a slash character «/» then the path is treated as absolute and the spec path replaces the context path. Otherwise, the path is treated as a relative path and is appended to the context path, as described in RFC2396. Also, in this case, the path is canonicalized through the removal of directory changes made by occurrences of «..» and «.». For a more detailed description of URL parsing, refer to RFC2396.
URL
public URL(URL context, String spec, URLStreamHandler handler) throws MalformedURLException
Creates a URL by parsing the given spec with the specified handler within a specified context. If the handler is null, the parsing occurs as with the two argument constructor.
Method Detail
getQuery
Руководство по Java URL
URL — это ссылка или адрес ресурса в сети. Проще говоря, Java-код, взаимодействующий по сети, может использовать классjava.net.URL для представления адресов ресурсов.
Платформа Java поставляется со встроенной сетевой поддержкой, включенной в пакетjava.net:
2. Создание URL
Давайте сначала создадим объектjava.net.URL, используя его конструктор и передав String, представляющий удобочитаемый адрес ресурса:
URL url = new URL("/a-guide-to-java-sockets");
Мы только что создалиabsolute URL object. В адресе есть все части, необходимые для достижения желаемого ресурса.
Мы также можем создатьa relative URL; предполагая, что у нас есть объект URL, представляющий домашнюю страницу примера:
URL home = new URL("http://example.com");
Затем давайте создадим новый URL, указывающий на уже известный нам ресурс. мы собираемся использовать другой конструктор, который принимает как существующий URL, так и имя ресурса относительно этого URL:
URL url = new URL(home, "a-guide-to-java-sockets");
Теперь мы создали новый объект URLurl относительноhome; поэтому относительный URL-адрес действителен только в контексте базового URL-адреса.
Мы можем увидеть это в тесте:
@Test public void givenBaseUrl_whenCreatesRelativeUrl_thenCorrect() < URL baseUrl = new URL("http://example.com"); URL relativeUrl = new URL(baseUrl, "a-guide-to-java-sockets"); assertEquals( "/a-guide-to-java-sockets", relativeUrl.toString()); >
Однако если обнаруживается, что относительный URL-адрес является абсолютным в своих составных частях, тоbaseURL игнорируется:
@Test public void givenAbsoluteUrl_whenIgnoresBaseUrl_thenCorrect() < URL baseUrl = new URL("http://example.com"); URL relativeUrl = new URL( baseUrl, "/a-guide-to-java-sockets"); assertEquals( "/a-guide-to-java-sockets", relativeUrl.toString()); >
Наконец, мы можем создать URL, вызвав другой конструктор, который принимает составляющие части строки URL. Мы рассмотрим это в следующем разделе после рассмотрения компонентов URL.
3. Компоненты URL
URL-адрес состоит из нескольких компонентов, которые мы рассмотрим в этом разделе.
Давайте сначала посмотрим на разделение идентификатора протокола и ресурса — эти два компонента разделяются двоеточием, за которым следуют две косые черты, т.е. ://.с
Если у нас есть URL-адрес, такой какhttp://example.com, тогда часть перед разделителем,http, — это идентификатор протокола, а следующий за ним — имя ресурса,example.com.
Давайте посмотрим на API, который предоставляет объектURL.
3.1. Протокол
Чтобы получитьthe protocol — мы используем методgetProtocol():
@Test public void givenUrl_whenCanIdentifyProtocol_thenCorrect()< URL url = new URL("http://example.com"); assertEquals("http", url.getProtocol()); >
3.2. Порт
Чтобы получитьthe port — воспользуемся методомgetPort():
@Test public void givenUrl_whenGetsDefaultPort_thenCorrect()< URL url = new URL("http://example.com"); assertEquals(-1, url.getPort()); assertEquals(80, url.getDefaultPort()); >
Обратите внимание, что этот метод извлекает явно определенный порт. Если порт не определен явно, он вернет -1.
И поскольку HTTP-связь использует порт 80 по умолчанию — порт не определен.
Вот пример, в котором у нас есть явно определенный порт:
@Test public void givenUrl_whenGetsPort_thenCorrect()< URL url = new URL("http://example.com:8090"); assertEquals(8090, url.getPort()); >
3.3. Гостья
The host — это часть имени ресурса, которая начинается сразу после разделителя:// и заканчивается расширением имени домена, в нашем случае.com.
Мы вызываем методgetHost() для получения имени хоста:
@Test public void givenUrl_whenCanGetHost_thenCorrect()< URL url = new URL("http://example.com"); assertEquals("example.com", url.getHost()); >
3.4. Имя файла
Все, что следует после имени хоста в URL-адресе, называетсяfile name of the resource. Он может включать как параметры пути и запроса, так и просто имя файла:
@Test public void givenUrl_whenCanGetFileName_thenCorrect1() < URL url = new URL("/guidelines.txt"); assertEquals("/guidelines.txt", url.getFile()); >
Предполагая, что в примере есть статьи java 8 под URL/articles?topic=java&version=8. Все после имени хоста является именем файла:
@Test public void givenUrl_whenCanGetFileName_thenCorrect2() < URL url = new URL( "/articles?topic=java&version=8"); assertEquals("/articles?topic=java&version=8", url.getFile()); >
3.5. Параметры пути
Мы также можем проверять только параметрыthe path, которые в нашем случае являются/articles:
@Test public void givenUrl_whenCanGetPathParams_thenCorrect() < URL url = new URL( "/articles?topic=java&version=8"); assertEquals("/articles", url.getPath()); >
3.6. Параметры запроса
Точно так же мы можем проверитьthe query parameters, который равенtopic=java&version=8:
@Test public void givenUrl_whenCanGetQueryParams_thenCorrect() < URL url = new URL("/articles?topic=java&version=8"); assertEquals("topic=java&version=8", url.getQuery()); >
4. Создание URL с составными частями
Поскольку теперь мы рассмотрели различные компоненты URL-адреса и их место в формировании полного адреса ресурса, мы можем рассмотреть другой способ создания объекта URL-адреса путем передачи частей компонента.
Первый конструктор принимает протокол, имя хоста и имя файла соответственно:
@Test public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect() < String protocol = "http"; String host = "example.com"; String file = "/guidelines.txt"; URL url = new URL(protocol, host, file); assertEquals("/guidelines.txt", url.toString()); >
Имейте в виду значение имени файла в этом контексте, следующий тест должен прояснить его:
@Test public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect2() < String protocol = "http"; String host = "example.com"; String file = "/articles?topic=java&version=8"; URL url = new URL(protocol, host, file); assertEquals("/guidelines.txt", url.toString()); >
Второй конструктор принимает протокол, имя хоста, номер порта и имя файла соответственно:
@Test public void givenUrlComponentsWithPort_whenConstructsCompleteUrl_ thenCorrect() < String protocol = "http"; String host = "example.com"; int port = 9000; String file = "/guidelines.txt"; URL url = new URL(protocol, host, port, file); assertEquals( "http://example.com:9000/guidelines.txt", url.toString()); >
5. Заключение
В этом руководстве мы рассмотрели классURL и показали, как использовать его в Java для программного доступа к сетевым ресурсам.
Как всегда, полный исходный код статьи и все фрагменты кода можно найти в папкеGitHub project.