Java Network programming URL, URLConnection, Urlencoder, urldecoder__ network programming

Source: Internet
Author: User

In Java network programming let us get a network address resources, we often use the URL Uniform Resource Locator (uniform Resource Locator), URL class Java.net.URL. The URL is defined as follows:

[Scheme :] scheme-specific-part[ # Fragment]

where the square brackets [...] are used to describe optional components, characters : and # represent themselves. View the API for more information.


A, URL

The main methods are as follows:

1. Construction method

The URL (string spec) creates a URL object based on a string representation.
The URL (string protocol, string host, int port, string file) creates a URL object based on the specified protocol, host, port, and file.

2, the commonly used methods

URLConnection OpenConnection () returns a URLConnection object that represents the connection to the remote object referenced by the URL.
InputStream OpenStream () opens a connection to this URL and returns a inputstream for reading from the connection.

For example, read the data of Baidu home page:

Package andy.network.test;

Import java.io.IOException;
Import Java.io.InputStream;
Import Java.net.URL;
Import Java.util.Scanner;

/**  
 * @author zhang,tianyou *  
 version:2014-11-24 PM 4:14:20 * * 
 * * * Public

class Urltest {

	/**
	 * @param args
	 * @throws ioexception
	/public static void main (string[] args) throws ioexception {
		
		url url = new URL ("http://www.baidu.com");
		URL Open gets an input stream
		inputstream in = Url.openstream ();
		Instantiate a Scanner
		Scanner Scanner = new Scanner (in);
		Sets the read separator
		scanner.usedelimiter ("\ n");
		while (Scanner.hasnext ()) {
			String str = Scanner.next ();
			System.out.println (str);}}



Second, URLConnection

URLConnection is a class that encapsulates access to remote resources through which you can establish a connection to a remote server and obtain and check the properties of a remote resource.

It contains HttpURLConnection, jarurlconnection two subclasses.

The main methods are as follows:

1. Construction method

protected urlconnection (URL url) constructs a URL connection to the specified URL.

2. Common methods
InputStream getInputStream () returns the input stream read from this open connection.
OutputStream Getoutputstream () returns the output stream written to this connection.
void setconnecttimeout (int timeout) sets a specified time-out value, in milliseconds, that will be used when opening a communication link to a resource referenced by this urlconnection.
int Getcontentlength () returns the value of the Content-length header field.
String getContentType () returns the value of the Content-type header field

Use the following example:

Package andy.network.test;

Import java.io.IOException;
Import java.net.MalformedURLException;
Import Java.net.URL;
Import java.net.URLConnection;
Import Java.util.concurrent.TimeUnit;

/**  
 * @author zhang,tianyou *  
 version:2014-11-24 PM 4:33:19 * * 
 * * Public

Class urlconnectiontest {

	/**
	 * @param args
	 * @throws ioexception
	/public static void main (String [] args throws ioexception {
		url url = new URL ("http://www.baidu.com");
		
		Get URLConnection
		URLConnection conn = Url.openconnection ();
		Set timeout time of more than 2 seconds
		Conn.setreadtimeout (Watts);
		
		System.out.println ("Get content Size:" + conn.getcontentlength ());
		System.out.println ("Get content Type:" + conn.getcontenttype ());

	}



Iii. Urlencoder and Urldncoder

Urlencoder and Urldncoder are mainly to complete the encoding and decoding of the content.

There are also the following methods:
The static string encode (string s, String enc) converts a string to a application/x-www-form-urlencoded format using the specified encoding mechanism.
The static string decode (string s, String enc) decodes the application/x-www-form-urlencoded string using the specified encoding mechanism.


Use the following:

Package andy.network.test;

Import java.io.UnsupportedEncodingException;
Import Java.net.URLDecoder;
Import Java.net.URLEncoder;

/**  
 * @author zhang,tianyou *  
 version:2014-11-24 PM 4:42:47 * * 
 * * Public

Class Urlencoderandurldecoder {

	/**
	 * @param args
	 * @throws unsupportedencodingexception
	* * public static void Main (string[] args) throws Unsupportedencodingexception {
		//decoder and encoded formats should be the same
		String coder = "U TF-8 ";
		String src = "Hello, Android";
		
		String enstr = Urlencoder.encode (src, coder);
		String destr = Urldecoder.decode (enstr, coder);
				
		SYSTEM.OUT.PRINTLN ("Encoded content:" + enstr);
		System.out.println ("Content after decoding:" + destr);
	}



The results of the execution are:

Post-encoded content: hello%ef%bc%8c%e5%ae%89%e5%8d%93+android
Content after decoding: Hello, Android


Related Article

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.