Java based on socket implementation HTTP download client _java

Source: Internet
Author: User
Tags file url ranges

A minimized HTTP file download client is implemented entirely based on Java sockets without any third-party libraries. A complete demo of how HTTP requests (Request headers) for downloading files through a socket is sent to receive HTTP responses (Response header, Response body) messages from the socket and to parse and save the contents of the file. How to implement UI refresh through Swingwork, real-time display download progress.

First look at the UI section:

Add Download button:

Click on the pop-up URL input box, user copy to download the file URL to the input box, click the [OK] button to start

Download


Clear Finish button:

Clear the list of all files that have been downloaded and completed

File download status is divided into the following categories:

Package com.gloomyfish.socket.tutorial.http.download; 
 
public enum Downloadstatus { 
  not_started, 
  in_process, 
  COMPLETED, 
  ERROR 
} 

The UI part is done primarily with swing components. Click "Add Download" to execute the following code:

Final JDialog Dialog = new JDialog (this, "Add File Link", true); 
Dialog.getcontentpane (). setlayout (New BorderLayout ()); 
Dialog.setsize (New Dimension (400,200)); 
Final Urlfilepanel panel = new Urlfilepanel (); 
Panel.setuplistener (new ActionListener () { 
  @Override public 
  void actionperformed (ActionEvent e) { 
    if ("OK '. Equals (E.getactioncommand ()) { 
      if (Panel.validateinput ()) { 
        Downloaddetailstatusinfomodel data = new Downloaddetailstatusinfomodel (Panel.getvalidfileurl ()); 
        Tablemodel.getdata (). Add (data); 
        Startdownlaod (); 
        Refreshui (); 
      } 
      Dialog.setvisible (false); 
      Dialog.dispose (); 
    } else if ("Cancel". Equals (E.getactioncommand ()) { 
      dialog.setvisible (false); 
      Dialog.dispose ();}} 
  ); 
 
Dialog.getcontentpane (). Add (Panel, borderlayout.center); 
Dialog.pack (); 
Centre (Dialog); 
Dialog.setvisible (TRUE); 

The Purge complete button executes the following code:

private void cleardownloaded () { 
  list<downloaddetailstatusinfomodel> downloadedlist = new arraylist< Downloaddetailstatusinfomodel> (); 
  For (Downloaddetailstatusinfomodel FileStatus:tableModel.getData ()) { 
    if (Filestatus.getstatus (). toString (). Equals (DownLoadStatus.COMPLETED.toString ())) { 
      downloadedlist.add (filestatus); 
    } 
  } 
  Tablemodel.getdata (). RemoveAll (downloadedlist); 
  Refreshui (); 
} 

The code to center the JFrame component is as follows:

public static void Centre (Window w) { 
  Dimension us = w.getsize (); 
  Dimension them = Toolkit.getdefaulttoolkit (). Getscreensize (); 
  int newx = (them.width-us.width)/2; 
  int newy = (them.height-us.height)/2; 
  W.setlocation (newx, newy); 
} 

HTTP protocol Implementation section:

Overview: Basic structure and explanation of HTTP request header and corresponding header message

HTTP request: A standard HTTP request message such as


Where the request header can have multiple, message-body can not, not necessarily. The format of the request line is as follows:

Request-line = Method SP Request-uri sphttp-version CRLF as illustrated below:

Request-line = Get http://www.w3.org/pub/www/theproject.htmlhttp/1.1\r\n

Where the SP represents a space, CRLF represents a carriage return line break \ r \ n

When you want to upload files, use the Post method to fill in the data into the message-body. Send a

The simple HTTP request message is as follows:

    • Get/pub/www/theproject.html http/1.1\r\n
    • Host: www.w3.org\r\n
    • \ r \ n

HTTP response: A standard HTTP response message is as follows


The first is the status line, which is formatted as follows:

Status-line = http-version SP status-codesp reason-phrase CRLF, a simple example of a status line is as follows: Status-line = http/1.1 ok generally, everyone likes statu. S-code will give you a lot of tips, the most common is 404,500 status code. The meaning of the status code can refer to the interpretation in RFC2616. Download files Most importantly, check the HTTP response header Content-length and Content-type two

The length of the file and the type of file are declared separately. Others, such as accept-ranges, indicate how many bytes to accept. May be used in multithreaded downloads. After making clear the HTTP request and the response message format, we can resolve the content through the socket according to the message format, send and read the HTTP request and the response. Specific steps

As follows:

A socket connection is established based on the file URL entered by the user

URL url = new URL (fileinfo.getfileurl ()); 
String host = Url.gethost (); 
int port = (Url.getport () = = 1)? Url.getdefaultport (): Url.getport (); 
System.out.println ("Host Name =" + host); 
System.out.println ("port =" + port); 
System.out.println ("File URI =" + Url.getfile ()); 
 
Create socket and start to construct the request line 
socket socket = new socket (); 
SocketAddress address = new Inetsocketaddress (host, Port); 

The URL class is used to turn the URL string entered by the user into a URL that is easy to parse.
Ii. Constructing HTTP requests

BufferedWriter bufferedwriter = new BufferedWriter (New OutputStreamWriter (Socket.getoutputstream (), "UTF8")); 
String requeststr = "Get" + url.getfile () + "http/1.1\r\n"; Request line 
 
//construct the request header-construct the HTTP request header (Request header) 
String hostheader = "Host:" + Host + "\ r \ n"; 
String AcceptHeader = "accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"; 
String Charsetheader = "accept-charset:gbk,utf-8;q=0.7,*;q=0.3\r\n"; 
String Languageheader = "accept-language:zh-cn,zh;q=0.8\r\n"; 
String Keepheader = "connection:close\r\n"; 

Third, send HTTP request

Send HTTP request 
Bufferedwriter.write (REQUESTSTR); 
Bufferedwriter.write (Hostheader); 
Bufferedwriter.write (AcceptHeader); 
Bufferedwriter.write (Charsetheader); 
Bufferedwriter.write (Languageheader); 
Bufferedwriter.write (Keepheader); 
Bufferedwriter.write ("\ r \ n"); The request header information sends the end sign 
bufferedwriter.flush (); 

Iv. Accept HTTP responses and parse the content to write the created file

prepares to accept HTTP response headers and resolves customdatainputstream input = new Customdatainputstream (Socket.getinputstream ()); 
File MyFile = new file (fileinfo.getstorelocation () + File.separator + fileinfo.getfilename ()); 
String content = null; 
Httpresponseheaderparser Responseheader = new Httpresponseheaderparser (); 
Bufferedoutputstream output = new Bufferedoutputstream (new FileOutputStream (MyFile)); 
Boolean hasData = false; while (content = Input.readhttpresponseheaderline ())!= null) {System.out.println ("Response header contect-->> 
  "+ content); 
  Responseheader.addresponseheaderline (content); 
  if (content.length () = = 0) {HasData = true; 
    } if (hasData) {int totalbytes = Responseheader.getfilelength (); if (totalbytes = = 0) break; 
    No response body and data int offset = 0; 
    byte[] MyData = null; 
    if (totalbytes >= 2048) {myData = new byte[2048]; 
    else {myData = new byte[totalbytes]; 
    int numofbytes = 0; while (numofBytes = Input.read (myData, 0, mydata.length)) > 0 && Offset < totalbytes) {offset = numofbytes; 
      float p = ((float) offset)/((float) totalbytes) * 100.0f; 
        if (Offset > totalbytes) {numofbytes = numofbytes + totalbytes-offset; 
      p = 100.0f; 
      } output.write (MyData, 0, numofbytes); 
    UpdateStatus (P); 
    } HasData = false; 
  Break 
 } 
}

The

Simple HTTP response Header parsing class Httpresponseheaderparser code is as follows:

Package com.gloomyfish.socket.tutorial.http.download; 
Import Java.util.HashMap; 
 
Import Java.util.Map; /** * It can parse entity header, Response head * and Response line <status code, CharSet, Ect...> * refer to 
 RFC2616, about HTTP response headers, please see the RFC document, described in detail AH!! 
  * * Public class Httpresponseheaderparser {public final static String content_length = "Content-length"; 
  Public final static String Content_Type = "Content-type"; 
   
  Public final static String accept_ranges = "Accetp-ranges"; 
  Private map<string, string> Headermap; 
  Public Httpresponseheaderparser () {headermap = new hashmap<string, string> (); }/** * <p> get the response header key value pair </p> * @param responseheaderline * * * publi c void Addresponseheaderline (String responseheaderline) {if (Responseheaderline.contains (":")) {string[] Keyv 
      Alue = Responseheaderline.split (":"); 
       if (Keyvalue[0].equalsignorecase (content_length)) { Headermap.put (Content_length, keyvalue[1]); 
      else if (Keyvalue[0].equalsignorecase (Content_Type)) {headermap.put (Content_Type, keyvalue[1]); 
      else {headermap.put (keyvalue[0], keyvalue[1]); 
    }} public int getfilelength () {if (Headermap.get (content_length) = = null) {return 0; 
  Return Integer.parseint (Headermap.get (content_length)); 
  Public String Getfiletype () {return headermap.get (content_type); 
  Public map<string, String> getallheaders () {return headermap;  } 
 
}

The above is the entire content of this article, I hope to learn Java program to help you.

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.