Java Core Learning (29) Basic Network support

Source: Internet
Author: User
Tags get ip fully qualified domain name

First, inetaddress

Java provides inetaddress for the IP address, which has two subclasses inet4address and Inet6address, respectively, representing the IPV4 and IPV6 addresses.

This class does not have a constructor, but instead uses two static factory methods to obtain the InetAddress instance

Getbyname (String host);

Getbyaddress (byte[] addr);

It's four main example methods

String getcanonicalhostname (); Gets the fully qualified domain name of the IP address

String gethostaddress (); Get IP Address

String gethostname (); Gets the host name of the IP address

Boolean isreachable (); Determines whether the IP address can be reached and can pass in a wait length as a parameter

Ii. Urldecoder and Urlencoder

These two classes are used to complete the conversion of a normal string to a application/x-www-form-urlencoded MIME string.

What is a application/x-www-form-urlencoded MIME string?

When a string containing non-Western European characters is included in the URL address, the system converts these non-western characters into a special string, so the URL received by the background needs to be decoded to a normal string, which is used by the Urldecoder, when the program sends the request, You need to convert the URL plain string encoding to a special string using Urlencoder.

The decoding and encoding is done using the static method of the two classes decode (string s, String enc), encode (string s, String enc), respectively. ENC is a character set.

Iii. URLs, URLConnection, and Urlpermission

These three APIs that should belong to the application layer

The following implementation of a multi-threaded download tool class to try out this API

Refer to the HTTP request header for detailed information

Package Net;import Java.io.file;import Java.io.filereader;import java.io.inputstream;import Java.io.randomaccessfile;import Java.net.httpurlconnection;import Java.net.url;import Java.nio.channels.filechannel;import Java.nio.charset.charset;import Java.nio.file.files;import Java.nio.file.path;import Java.nio.file.paths;import Java.util.arraylist;import Java.util.List;public class  Downutil {private String path;  Download the path to the resource private String targetfile;    private int threadnum;    Private downthread[] threads;    private int filesize;    Private final String Infofilesuffix = "INI.txt";        Public Downutil (string path, string targetfile, int threadnum) {this.path = path;        This.targetfile = TargetFile;    This.threadnum = Threadnum;        } public Downutil (string path, String targetfile) {This.path = path;        This.targetfile = TargetFile; This.threadnum = Runtime.getruntime (). Availableprocessors ();//The thread that opens the current machine CPU number by default} public void Download ()Throws exception{//build HTTP request get file size URL url = new URL (path);        HttpURLConnection conn = (httpurlconnection) url.openconnection ();        Conn.setrequestmethod ("GET");        Conn.setrequestproperty ("Accept", "*/*");        Conn.setrequestproperty ("Accept-language", "ZH-CN");        Conn.setrequestproperty ("Charset", "UTF-8");        Conn.setrequestproperty ("Connection", "keep-alive"); FileSize = Conn.getcontentlength ();        Get file size conn.disconnect (); Assign the download task to each thread int currentpartsize = filesize/threadnum + 1;        The size of the file block that each thread is responsible for is path PATH = Paths.get (Targetfile+infofilesuffix); if (files.exists (path)) {//Read file contents continue to download list<string> allline = files.readalllines (path, CHARSET.F            ORName ("UTF-8"));                for (int i = 0; i < threadnum; i++) {int startpos = i * currentpartsize;                Randomaccessfile Currentpart = new Randomaccessfile (targetfile, "RW"); Currentpart.seek (STARtpos);                Threads[i] = new Downthread (Startpos,currentpartsize,currentpart,integer.parseint (Allline.get (i). toString ()));            Threads[i].start ();            }}else {Randomaccessfile file = new Randomaccessfile (targetfile, "RW");            File.setlength (filesize);            File.close ();            list<string> infostrings = new arraylist<> ();            for (int i = 0; i < threadnum; i++) {Infostrings.add ("0");            } files.write (Path,infostrings,charset.forname ("UTF-8"));                for (int i = 0; i < threadnum; i++) {int startpos = i * currentpartsize;                Randomaccessfile Currentpart = new Randomaccessfile (targetfile, "RW");                Currentpart.seek (startpos);                Threads[i] = new Downthread (Startpos,currentpartsize,currentpart);            Threads[i].start (); }//re-write file}} private class Downthread Extends thread{private int startpos;//When the front-thread begins to download the location of the private int currentpartsize;  The current thread is responsible for downloading the size of private randomaccessfile currntpart; The current thread needs to download the file class public int length;        The number of bytes downloaded, if you want to implement a breakpoint download, it is possible that this data exists on the hard disk, that is, there is a file in the private final String acceptstring = "*/*";        Private final String charsetstring = "UTF-8";        Private final String acceptlanguagestring = "ZH-CN"; Public downthread (int startpos, int currentpartsize, randomaccessfile currntpart,int length) {This.startpos =            startpos;            This.currentpartsize = currentpartsize;            This.currntpart = Currntpart;        this.length = length; } public downthread (int startpos, int currentpartsize, Randomaccessfile currrntpart) {this.startpos = St            ArtPos;            This.currentpartsize = currentpartsize;            This.currntpart = Currrntpart;        this.length = 0;              } @Override public void Run () {try {  URL url = new URL (path);                HttpURLConnection conn = (httpurlconnection) url.openconnection ();                Conn.setconnecttimeout (5000);                Conn.setrequestmethod ("GET");                Conn.setrequestproperty ("Accept", acceptstring);                Conn.setrequestproperty ("Charset", charsetstring);                Conn.setrequestproperty ("Accept-language", acceptlanguagestring);                Conn.setrequestproperty ("Range", "bytes=" + (startpos + length) + "-" + (Startpos + currentPartSize-1));                InputStream InputStream = Conn.getinputstream ();                byte[] buffer = new byte[1024]; int hasread = 0;                    Number of bytes read at a time while (length < currentpartsize && (Hasread = inputstream.read (buffer))! =-1) {                    Currntpart.write (Buffer,0,hasread);                length + = Hasread;                } currntpart.close ();            Inputstream.close (); }catch (Exceptione) {e.printstacktrace (); }        }    }}

The above code can also increase the breakpoint continuation download function, this code basically shows the URL and urlconniction (abstract class) The use of two classes

And Urlpermission is the JAVA8 new tool class, used to manage the Httpurlconniction permissions problem, if not to repeat the building of the wheel is basically not used, that is, to use also in the use of the time to view the document (Java too many classes).

  

Java Core Learning (29) Basic Network support

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.