Java Learning Summary (essay)--using JSON parsing to achieve network download

Source: Internet
Author: User

Using JSON for network download
1. Download the JSON string:
(1) Encapsulate URLs into URLs: url url=new url ("url");
(2) using the URL to open http:httpurlconnection conn= (httpurlconnection) ulr.openconnection ();
(3) Start connection: Conn.connect ();
(4) using the input stream to read the network data;
(5) Convert the downloaded data into a byte array;
2. Download the required resources: the same as the above steps, finally using the output stream, write to the destination address
Example 1 (we take the download image as an example (detailed instructions in the note)):
(1) First introduce JAR package
(2) Let's look at the target JSON we're going to download first.
Destination JSON address:
Http://open.qyer.com/qyer/recommands/index?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v =1&track_deviceid=860806022766611&track_app_version=5.1.1&track_app_channel=360m&track_device_ info=mx2&track_os=android4.2.1&track_user_id=&app_installtime=1404882938883%20http/1.1
Using the online JSON check format allows us to see the composition of the JSON string
(3) Write code:
Download Tool Class (contains two methods for downloading JSON strings and pictures):

Package Org.download.photo;import Java.io.bytearrayoutputstream;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.io.outputstream;import java.net.HttpURLConnection;        Import Java.net.url;public class Downloadutil {///JSON string download public static string Downloadjson (string path) {        URL url = null;        InputStream input = null;        HttpURLConnection conn = null;        byte date[] = null; try {url = new URL (path);//1. Encapsulate URLs into URLs conn = (httpurlconnection) url.openconnection ();//2. Turn on HTT P Connect conn.connect ();//3. Start Connection input = Conn.getinputstream ();//4. Gets the network input stream for reading the content to download Bytearr            Ayoutputstream BOS = new Bytearrayoutputstream ();//5. Get byte conversion stream byte[] B = new byte[1024];            int len = 0;            while (len = Input.read (b))! =-1) {bos.write (b, 0, Len);        } date = Bos.tobytearray ();          } catch (Exception e) {  E.printstacktrace ();            } finally {try {input.close ();            } catch (IOException e) {e.printstacktrace ();    }} return new String (date);        }//Download picture public static void Downloadphoto (String photo,string dest) {URL url = null;        InputStream input = null;        HttpURLConnection conn = null;        OutputStream Out=null;        byte date[] = null;            try {out=new fileoutputstream (dest); url = new URL (photo);//1. Encapsulate URLs into URLs conn = (httpurlconnection) url.openconnection ();//2. Open HTTP connection C Onn.connect ();//3. Start Connection input = Conn.getinputstream ();//4. Gets the network input stream for reading the content to download Bytearrayoutputstream b            OS = new Bytearrayoutputstream ();//5. Get byte conversion stream byte[] B = new byte[1024];            int len = 0;            while (len = Input.read (b))! =-1) {bos.write (b, 0, Len); } date = Bos.tobytearray ();            Out.write (date); System.out.println (dest+ "Picture download succeeded to write to local disk:");}        catch (Exception e) {e.printstacktrace ();                } finally {try {input.close ();            Out.close ();            } catch (IOException e) {e.printstacktrace (); }        }    }}

Download Test Class (Main method):

Package Org.download.photo;import Java.io.file;import Org.json.jsonarray;import org.json.jsonexception;import Org.json.jsonobject;public class Downloadtest {public static void main (string[] args) {//1. Download the JSON string S Tring Path = "http://open.qyer.com/qyer/recommands/index?client_id=qyer_android&client_secret= 9fcaae8aefc4f9ac4915&v=1&track_deviceid=860806022766611&track_app_version=5.1.1&track_app_ Channel=360m&track_device_info=mx2&track_os=android4.2.1&track_user_id=&app_installtime=        1404882938883%20http/1.1 ";        String jsonstr = Downloadutil.downloadjson (path); System.out.println (JSONSTR);//test whether the JSON string was successfully downloaded//2. Parse the JSON string to get the photo data (used here for official parsing) try {//3.            JSON string converted to Java object jsonobject jsonobj = new Jsonobject (JSONSTR);  4. Obtain value values Jsonobject Jsondata = jsonobj.optjsonobject ("Data") based on the key value;//Get the data object (first-level directory) Jsonarray Jsonplace = Jsondata.optjsonarray ("PlacE ");//Get the array form of place (Level two directory)//array form jsonplace, get photo data for (int i = 0; i < jsonplace.length (); i+ +) {Jsonobject Jsonob = Jsonplace.optjsonobject (i);//Gets the individual objects in the array String photostr = JSONOB.O                Ptstring ("photo");//Gets the photo string string[] Picarray = Photostr.split ("/"); 5. Start to download the picture and name it Downloadutil.downloadphoto (Photostr, "e:" + File.separator + "Myph            Oto "+file.separator+ picarray[picarray.length-1]);        }} catch (Jsonexception e) {e.printstacktrace (); }    }}

(4) Operation result:

Example 2 (download network pictures, without JSON parsing, set up a download interface, callback interface):
(1) Write code:
Download interface:

package org.download.nettu;//回调接口public interface Load {    void load(byte[] b);}

Download Method Class:

Package Org.download.nettu;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import  Java.io.inputstream;import Java.net.httpurlconnection;import Java.net.url;public class DownloadUtilPic {//Picture public        static void Downloadphoto (String path,load Load) {//1. URL is encapsulated in URL url=null;        InputStream Input=null;        HttpURLConnection Conn=null;             try {url=new URL (path); Conn= (HttpURLConnection) url.openconnection (); Get Network Connection object Conn.connect ();//Turn on network connection Input=conn.getinputstream ();//Get network input stream bytearrayoutputs            Tream bos=new Bytearrayoutputstream ();            int len=0;            Byte[] B=new byte[1024];            while ((Len=input.read (b))!=-1) {bos.write (b, 0, Len);            }//Convert the downloaded data into a byte array byte[] date= bos.tobytearray (); Load.load (date);        Callback Load Method} catch (Exception e) {e.printstacktrace (); }finally{try {                Input.close ();            } catch (IOException e) {e.printstacktrace (); }        }    }}

Test Download Class (Main method):

Package Org.download.nettu;import Java.io.bufferedoutputstream;import Java.io.file;import Java.io.FileOutputStream Import Java.io.ioexception;import Java.io.outputstream;public class Downloadtest {public static void main (string[] Ar        GS) {String path= "http://static.qyer.com/upload/mobile/operation/6e/e1/6ee105f770fe63f625422912b1465e2e.jpg"; Call the Download method Downloadutilpic.downloadphoto (path, new Load () {@Override public void Load (byte                [] b) {OutputStream out=null;                    try {out=new FileOutputStream ("F:" +file.separator+ "abcdgdh.jpg");                    Bufferedoutputstream bos=new Bufferedoutputstream (out);                    Bos.write (b); System.out.println ("Picture downloaded successfully.                ");                } catch (Exception e) {e.printstacktrace ();                    }finally{try {out.close ();      } catch (IOException e) {                  E.printstacktrace ();    }                }            }        }); }}

Operation Result:

Java Learning Summary (essay)--using JSON parsing to achieve network download

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.