JAva進級ノートのURIとURL.md
58493 ワード
概要
URLとURIは物理的な直接的なつながりがない(継承と実現ではない). URL=Universal Resource Locator=Universal Resource Locator=Universal Resource Locator=Universal Resource Locator(jdk 1.0が表示されます) は、ネットワークを介してあるリソースの識別子を特定およびアクセスする. ネットワークリソースロケーションは、通常、http、ftpなどのサーバにアクセスするためのプロトコル、サーバのホスト名またはIPアドレス、およびサーバ上のリソースファイルのパスを含む. は、ファイル、データなどの位置決めおよびアクセスを行うことができる. URLの構文表現形式は: URLのユーザ情報(userInfo)は、サーバのログイン情報であり、この情報はオプションである.この情報が存在する場合、通常はユーザー名が含まれ、パスワードが含まれることはほとんどありません.実際にURLがユーザー情報を携帯するのは安全ではありません. 例:http://username:[email protected]/test/blah?something=123
フラグメント(fragment)は、リモート・サーバ・リソースの特定の部分を表す.サーバリソースがHTMLドキュメントである場合、このフラグメント識別子はHTMLドキュメントのアンカーとして作成されます.リモートリソースがXMLドキュメントの場合、このフラグメント識別子はXPointerです.(Markdownでブログを書いたことがあればわかりますが、ナビゲーションディレクトリを追加すると、クリップはディレクトリがナビゲートする目的の章です) 相対URL 相対URLが「/」で始まると、現在のドキュメントではなく、ドキュメントに対するルートディレクトリになります.
エスケープ後のURLは、以前のnot equalと http://foo.com/hello world/and http://foo.com/hello%20world would be considered not equal to each other.
URI=Universal ResourceIdentifier=統合リソースフラグ(jdk 1.4が表示されます) コアは、リソースの一意性を示すリソースの文字列表現であり、定義されたフォーマット がある. URIの構文構成は、1つのモードと1つのモードの特定の部分である scheme:scheme specific part
URIは、URLに対してアクセス方式の保持一意識別子(アクセスアドレスがある可能性がある)を除去した抽象として簡単に理解できる. URI共通モード data:BASE 64によって符号化されたデータがリンクに直接含まれる. file:ローカルディスク上のファイル. ftp:FTPサーバ. http:ハイパーテキスト転送プロトコルを使用します. mailto:電子メールのアドレス. magnet:BitTorrentのようなピアツーピアネットワーク(BitTorrent)を介してダウンロードできるリソース. telnet:Telnetベースのサービスの接続. urn:統合リソース名(Uniform ResourceName).
javaでは、rmi、jar、jndi、doc、jdbcなどの などの非標準的なカスタマイズモードも多く使用されています. URIのパターン特定部分には固定的な文法はないが, のような階層形式を採用することが多い. URI構成内容:scheme,scheme-specific-part,authority,user-info,host,port,path,query,fragment 例
URN関連 URIは、ロケータ(URL)、名前(URN)または両方を兼ね備えていると見なすことができる.統合リソース名(URN)は、1人の名前のようなものであり、統合リソースロケータ(URL)は、1人の住所(およびアクセス方法)を表す.言い換えれば、URNはあるもののアイデンティティを定義し、URLはそのものを探す方法を提供する.
URL
メンバーの概要
変数&定数 String protocol=アクセスプロトコル:http など String authority = The authority part of this URL デフォルトauthority=host+":"+port String userInfo = The userinfo part of this URL String file = path + query String ref=fragment対応値 デフォルトプロトコル:BUILTIN_HANDLERS_PREFIX = “sun.net.www.protocol” デフォルトpath:protocolPathProp="java.protocol.handler.pkgs" 構築方法絶対パスの作成方法 相対パスの作成方法
一般的な方法はqueryに対して;path ; userInfo ; authority ; port ; protocol ; host ; file ; refなどの属性のgetメソッド. toStringおよびtoExternalForm toURI()
接続の取得
アクセス
StreamHandlerFactory
demo例
出力:
URI
URIインスタンスは、比較、正規化、解析、相対化などの構文的モードに関係のない動作をサポートする構造化された文字列です.
コアメソッド
メンバー&変数
こうぞう
構築方法は実際にParserの構築方法を呼び出します.Parserでは、各メンバーを解析する方法と、結果値を取得する方法が提供する.
一般的な方法
normalize()
resolve()
relativize()
toURL
demo例
出力結果:
URLを得るいくつかの方法
参照 Javaネットワークプログラミング-URIとURLhttps://www.cnblogs.com/throwable/p/9740425.html Javaの中の資源、URI、URL、経路とファイルはどんな違いがありますhttps://cloud.tencent.com/developer/ask/56385
URLとURIは物理的な直接的なつながりがない(継承と実現ではない).
protocol://userInfo@host:port/path?query#fragment
:// @ : / ? #
// / ?
//authority/path?query
mailto:[email protected]
news:comp.lang.java
urn:isbn:096139210x
https://docs.oracle.com/javase/1.3/docs/guide/collections/designfaq.html#28
URL
メンバーの概要
変数&定数
/**
*
* @param protocol the name of the protocol to use.
* @param host the name of the host.
* @param port the port number on the host. -1,
* protocol
* @param file the file on the host
* @param handler the stream handler for the URL. null ,
* protocol handler
* @exception MalformedURLException if an unknown protocol is specified.
* port URLStreamHandler URL
*/
public URL(String protocol, String host, int port, String file,
URLStreamHandler handler) throws MalformedURLException { ..... }
/**
* @param context the context in which to parse the specification.
* @param spec the {@code String} to parse as a URL.
* @param handler the stream handler for the URL.
*/
public URL(URL context, String spec, URLStreamHandler handler)
throws MalformedURLException
{ ... }
一般的な方法
/**
* URL
*/
public String toString() {
return toExternalForm();
}
/**
* URL
*/
public String toExternalForm() {
return handler.toExternalForm(this);
}
/**
* URL {@link java.net.URI}。
* {@code new URI (This . tostring())} 。 ,
* RFC2396 URL URI。 , url URI。
* @return a URI instance equivalent to this URL.
* @since 1.5
*/
public URI toURI() throws URISyntaxException {
return new URI (toString());
}
接続の取得
/**
* {@link java.net.URLConnection URLConnection} ,
* {@code URL} 。
* URL {@linkplain java.net
* .URLConnection URLConnection} ,
* {@linkplain java.net.URLConnection URLConnection}。
* ,URLConnection 。
* {@linkplain java.net.URLConnection#connect()
* URLConnection.connect()} 。
*
* URL ( HTTP JAR), 、 URLConnection ,
* :java.lang,java.io, java.net,
* 。 , HTTP, HttpURLConnection
*/
public URLConnection openConnection() throws java.io.IOException {
return handler.openConnection(this);
}
/**
*
* @since 1.5
*/
public URLConnection openConnection(Proxy proxy)
throws java.io.IOException { ... }
アクセス
/**
* Opens a connection to this {@code URL} and returns an
* {@code InputStream} for reading from that connection.
*/
public final InputStream openStream() throws java.io.IOException {
return openConnection().getInputStream();
}
// ps: ContentHandlerFactory
//, InputStream ; HTTP MIME TYPE
public final Object getContent() throws java.io.IOException {
return openConnection().getContent();
}
public final Object getContent(Class[] classes) throws java.io.IOException {
return openConnection().getContent(classes);
}
StreamHandlerFactory
/**
* {@code URLStreamHandlerFactory}。
* Java , 。
* {@code URLStreamHandlerFactory} 。
* , {@code checkSetFactory}
* 。 SecurityException。
*/
public static void setURLStreamHandlerFactory(URLStreamHandlerFactory fac) {
synchronized (streamHandlerLock) {
if (factory != null) {
throw new Error("factory already defined");
}
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkSetFactory();
}
handlers.clear();
factory = fac;
}
}
demo例
import org.junit.Test;
import java.net.MalformedURLException;
import java.net.URL;
public class URLTest {
@Test
public void test001() throws MalformedURLException {
URL url = new URL("http://username:[email protected]/test/blah?something=123#fra");
println("authority" ,url.getAuthority());
println("file", url.getFile());
println("dPort", url.getDefaultPort());
println("path", url.getPath());
println("protocol", url.getProtocol());
println("query", url.getQuery());
println("ref", url.getRef());
println("host", url.getHost());
println("userInfo", url.getUserInfo());
println("userInfo", url.getUserInfo());
println("toString", url.toString());
println("toExternalForm", url.toExternalForm());
System.out.println(".............................");
URL reUrl = new URL(url,"/relative");
println("path", reUrl.getPath());
println("file", reUrl.getFile());
println("toString", reUrl.toString());
println("toExternalForm", reUrl.toExternalForm());
}
private void println(String title,Object object){
System.out.println(title + ": " + object);
}
}
出力:
authority: username:[email protected]
file: /test/blah?something=123
dPort: 80
path: /test/blah
protocol: http
query: something=123
ref: fra
host: api.somesite.com
userInfo: username:password
userInfo: username:password
toString: http://username:[email protected]/test/blah?something=123#fra
toExternalForm: http://username:[email protected]/test/blah?something=123#fra
.............................
path: /relative
file: /relative
toString: http://username:[email protected]/relative
toExternalForm: http://username:[email protected]/relative
URI
URIインスタンスは、比較、正規化、解析、相対化などの構文的モードに関係のない動作をサポートする構造化された文字列です.
コアメソッド
メンバー&変数
// Components of all URIs: [:][#]
private transient String scheme; // null ==> relative URI
private transient String fragment;
// Hierarchical URI components: [//][?]
private transient String authority; // Registry or server
// Server-based authority: [@][:]
private transient String userInfo;
private transient String host; // null ==> registry-based
private transient int port = -1; // -1 ==> undefined
// Remaining components of hierarchical URIs
private transient String path; // null ==> opaque
private transient String query;
// The remaining fields may be computed on demand
private volatile transient String schemeSpecificPart;
こうぞう
public URI(String str) throws URISyntaxException {
new Parser(str).parse(false);
}
//ps: ssp = scheme-specific-part ,
public URI(String scheme, String ssp, String fragment)
throws URISyntaxException
{
new Parser(toString(scheme, ssp,
null, null, null, -1,
null, null, fragment))
.parse(false);
}
public static URI create(String str) {
try {
return new URI(str);
} catch (URISyntaxException x) {
throw new IllegalArgumentException(x.getMessage(), x);
}
}
//ps: , ,
public URI(String scheme,
String userInfo, String host, int port,
String path, String query, String fragment)
throws URISyntaxException
{
String s = toString(scheme, null,
null, userInfo, host, port,
path, query, fragment);
checkPath(s, scheme, path);
new Parser(s).parse(true);
}
構築方法は実際にParserの構築方法を呼び出します.Parserでは、各メンバーを解析する方法と、結果値を取得する方法が提供する.
一般的な方法
parseServerAuthority -> Parser
normalize()
/**
* URI 。 URI , , URI。
* , URI URI
* @return URI URI,
*/
public URI normalize() {
return normalize(this);
}
resolve()
/**
* ps: URI , / URI
* @return URI
*/
public URI resolve(URI uri) {
return resolve(this, uri);
}
public URI resolve(String str) {
return resolve(URI.create(str));
}
relativize()
/**
* ps: URI URI URL
*/
public URI relativize(URI uri) {
return relativize(this, uri);
}
toURL
public URL toURL()
throws MalformedURLException {
if (!isAbsolute())
throw new IllegalArgumentException("URI is not absolute");
return new URL(toString());
}
demo例
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
public class URITest {
@Test
public void test001() throws MalformedURLException, URISyntaxException {
//URL : %22 =
URI uri = new URI("ftp://username:[email protected]:99/test/blah?something=%22123%22#fra");
println("getAuthority" ,uri.getAuthority());
println("getFragment", uri.getFragment());
println("getHost", uri.getHost());
println("getPath", uri.getPath());
println("getPort", uri.getPort());
println("getQuery", uri.getQuery());
println("getRawAuthority", uri.getRawAuthority());
println("getRawFragment", uri.getRawFragment());
println("getRawPath", uri.getRawPath());
println("getRawQuery", uri.getRawQuery());
println("getRawSchemeSpecificPart", uri.getRawSchemeSpecificPart());
println("getRawUserInfo", uri.getRawUserInfo());
println("toASCIIString", uri.toASCIIString());
println("toString", uri.toString());
println("toURL", uri.toURL());
println("isAbsolute", uri.isAbsolute());
System.out.println(".............................");
URI reUri = URI.create("/relative");
println("toString", reUri.toString());
// uri reUri
reUri = uri.resolve(reUri);
println("toString", reUri.toString());
}
private void println(String title,Object object){
System.out.println(title + ": " + object);
}
出力結果:
getAuthority: username:password@api.somesite.com:99
getFragment: fra
getHost: api.somesite.com
getPath: /test/blah
getPort: 99
getQuery: something="123"
getRawAuthority: username:password@api.somesite.com:99
getRawFragment: fra
getRawPath: /test/blah
getRawQuery: something=%22123%22
getRawSchemeSpecificPart: //username:[email protected]:99/test/blah?something=%22123%22
getRawUserInfo: username:password
toASCIIString: ftp://username:password@api.somesite.com:99/test/blah?something=%22123%22#fra
toString: ftp://username:password@api.somesite.com:99/test/blah?something=%22123%22#fra
toURL: ftp://username:password@api.somesite.com:99/test/blah?something=%22123%22#fra
isAbsolute: true
.............................
toString: /relative
toString: ftp://username:password@api.somesite.com:99/relative
URLを得るいくつかの方法
URL systemResource = ClassLoader.getSystemResource(String name)
Enumeration<URL> systemResources = ClassLoader.getSystemResources(String name)
URL resource = UrlMain.class.getResource(String name)
URL resource = UrlMain.class.getClassLoader().getResource(String name)
Enumeration<URL> resources = UrlMain.class.getClassLoader().getResources(String name)
参照