Java get url param

Java get url param

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.

Читайте также:  Index php action user

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
  1. 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.
  2. 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

Источник

Parsing a URL

The URL class provides several methods that let you query URL objects. You can get the protocol, authority, host name, port number, path, query, filename, and reference from a URL using these accessor methods:

getProtocol Returns the protocol identifier component of the URL. getAuthority Returns the authority component of the URL. getHost Returns the host name component of the URL. getPort Returns the port number component of the URL. The getPort method returns an integer that is the port number. If the port is not set, getPort returns -1. getPath Returns the path component of this URL. getQuery Returns the query component of this URL. getFile Returns the filename component of the URL. The getFile method returns the same as getPath , plus the concatenation of the value of getQuery , if any. getRef Returns the reference component of the URL.

Remember that not all URL addresses contain these components. The URL class provides these methods because HTTP URLs do contain these components and are perhaps the most commonly used URLs. The URL class is somewhat HTTP-centric.

You can use these getXXX methods to get information about the URL regardless of the constructor that you used to create the URL object.

The URL class, along with these accessor methods, frees you from ever having to parse URLs again! Given any string specification of a URL, just create a new URL object and call any of the accessor methods for the information you need. This small example program creates a URL from a string specification and then uses the URL object’s accessor methods to parse the URL:

import java.net.*; import java.io.*; public class ParseURL < public static void main(String[] args) throws Exception < URL aURL = new URL("http://example.com:80/docs/books/tutorial" + "/index.html?name=networking#DOWNLOADING"); System.out.println("protocol = " + aURL.getProtocol()); System.out.println("authority = " + aURL.getAuthority()); System.out.println("host = " + aURL.getHost()); System.out.println("port = " + aURL.getPort()); System.out.println("path = " + aURL.getPath()); System.out.println("query = " + aURL.getQuery()); System.out.println("filename = " + aURL.getFile()); System.out.println("ref = " + aURL.getRef()); >>

Here is the output displayed by the program:

protocol = http authority = example.com:80 host = example.com port = 80 path = /docs/books/tutorial/index.html query = name=networking filename = /docs/books/tutorial/index.html?name=networking ref = DOWNLOADING

Источник

Java get url param

  • Language
  • HTML & CSS
  • Form
  • Java interaction
  • Mobile
  • Varia
  • Language
  • String / Number
  • AWT
  • Swing
  • Environment
  • IO
  • JS interaction
  • JDBC
  • Thread
  • Networking
  • JSP / Servlet
  • XML / RSS / JSON
  • Localization
  • Security
  • JNI / JNA
  • Date / Time
  • Open Source
  • Varia
  • Powerscript
  • Win API & Registry
  • Datawindow
  • PFC
  • Common problems
  • Database
  • WSH & VBScript
  • Windows, Batch, PDF, Internet
  • BigIndex
  • Download
  • TS2068, Sinclair QL Archives
  • Real’s HowTo FAQ
  • Donate!
  • Funny 1
  • Funny 2
  • Funny 3
  • Funny 4
  • One line
  • Ascii Art
  • Deprecated (old stuff)

    Get URL parameters using JDK HTTP server Tag(s): Networking

    About cookies on this site

    We use cookies to collect and analyze information on site performance and usage, to provide social media features and to enhance and customize content and advertisements.

    The server is very simple. If you want to access parameters passed in the URL (using the GET method) then you need to provide a method to extract them.

    import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; public class SimpleHttpServer2 < public static void main(String[] args) throws Exception < HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0); server.createContext("/info", new InfoHandler()); server.createContext("/get", new GetHandler()); server.setExecutor(null); // creates a default executor server.start(); System.out.println("The server is running"); >// http://localhost:8000/info static class InfoHandler implements HttpHandler < public void handle(HttpExchange httpExchange) throws IOException < String response = "Use /get?hello=word&foo=bar to see how to handle url parameters"; SimpleHttpServer2.writeResponse(httpExchange, response.toString()); >> static class GetHandler implements HttpHandler < public void handle(HttpExchange httpExchange) throws IOException < StringBuilder response = new StringBuilder(); Map parms = SimpleHttpServer2.queryToMap(httpExchange.getRequestURI().getQuery()); response.append(""); response.append("hello : " + parms.get("hello") + "
    "); response.append("foo : " + parms.get("foo") + "
    "); response.append(""); SimpleHttpServer2.writeResponse(httpExchange, response.toString()); > > public static void writeResponse(HttpExchange httpExchange, String response) throws IOException < httpExchange.sendResponseHeaders(200, response.length()); OutputStream os = httpExchange.getResponseBody(); os.write(response.getBytes()); os.close(); > /** * returns the url parameters in a map * @param query * @return map */ public static Map queryToMap(String query) < Mapresult = new HashMap(); for (String param : query.split("&")) < String pair[] = param.split("="); if (pair.length>1) < result.put(pair[0], pair[1]); >else < result.put(pair[0], ""); >> return result; > >

    Источник

Оцените статью