Java學習總結(隨筆)——利用JSON解析實現網絡下載
阿新 • • 發佈:2018-06-15
磁盤 bcd 數據 寫入 取數 mobile exce new mage 利用JSON實現網絡下載
1.下載json字符串:
(1)將網址封裝到URL中:URL url=new URL(“網址”);
(2)利用url打開HTTP: HttpURLConnection conn= (HttpURLConnection)ulr.openConnection();
(3)開始連接:conn.connect();
(4)利用輸入流讀取網絡數據;
(5)將下載的數據轉換成字節數組;
2.下載所需資源:與上述步驟相同,最後利用輸出流,寫入到目標地址
例1(我們以下載圖片為例(註釋中詳細的說明了操作步驟)):
(1)先引入jar包
(2)我們先觀察一下我們要下載的目標JSON
目標JSON地址:
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
使用在線JSON校驗格式,便於我們觀察JSON字符串的組成
(3)編寫代碼:
下載工具類(包含下載JSON字符串和圖片的兩個方法):
1.下載json字符串:
(1)將網址封裝到URL中:URL url=new URL(“網址”);
(2)利用url打開HTTP: HttpURLConnection conn= (HttpURLConnection)ulr.openConnection();
(3)開始連接:conn.connect();
(4)利用輸入流讀取網絡數據;
(5)將下載的數據轉換成字節數組;
2.下載所需資源:與上述步驟相同,最後利用輸出流,寫入到目標地址
例1(我們以下載圖片為例(註釋中詳細的說明了操作步驟)):
(1)先引入jar包
(2)我們先觀察一下我們要下載的目標JSON
目標JSON地址:
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
(3)編寫代碼:
下載工具類(包含下載JSON字符串和圖片的兩個方法):
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字符串下載 public static String downloadJSON(String path) { URL url = null; InputStream input = null; HttpURLConnection conn = null; byte date[] = null; try { url = new URL(path);// 1.將網址封裝到URL中 conn = (HttpURLConnection) url.openConnection();// 2.打開http連接 conn.connect();// 3.開始連接 input = conn.getInputStream();// 4.獲取網絡輸入流,用於讀取要下載內容 ByteArrayOutputStream bos = new ByteArrayOutputStream();// 5.獲取字節轉換流 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); } //下載圖片 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.將網址封裝到URL中 conn = (HttpURLConnection) url.openConnection();// 2.打開http連接 conn.connect();// 3.開始連接 input = conn.getInputStream();// 4.獲取網絡輸入流,用於讀取要下載內容 ByteArrayOutputStream bos = new ByteArrayOutputStream();// 5.獲取字節轉換流 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+"圖片下載成功,以寫入本地磁盤.."); } catch (Exception e) { e.printStackTrace(); } finally { try { input.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
下載測試類(主方法):
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.下載JSON字符串 String 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);//測試JSON字符串是否下載成功 // 2.解析JSON字符串,獲取到photo數據(此處使用官方解析) try { // 3.將JSON字符串轉化為java對象 JSONObject jsonObj = new JSONObject(jsonStr); // 4.根據key值獲取value值 JSONObject jsonData = jsonObj.optJSONObject("data");// 先獲取data對象(一級目錄) JSONArray jsonPlace = jsonData.optJSONArray("place");// 再獲取數組形式的place(二級目錄) // 數組形式的jsonPlace,獲取photo數據 for (int i = 0; i < jsonPlace.length(); i++) { JSONObject jsonOb = jsonPlace.optJSONObject(i);// 獲取數組中的各個對象 String photoStr = jsonOb.optString("photo");// 獲取其中的photo字符串 String[] picArray = photoStr.split("/"); // 5.開始下載圖片,並為其命名 DownloadUtil.downloadPhoto(photoStr, "e:" + File.separator + "myphoto" +File.separator+ picArray[picArray.length - 1]); } } catch (JSONException e) { e.printStackTrace(); } } }
(4)運行結果:
例2(下載網絡圖片,不用JSON解析,建立下載接口,回調接口):
(1)編寫代碼:
下載接口:
package org.download.nettu;
//回調接口
public interface Load {
void load(byte[] b);
}
下載方法類:
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 {
//圖片
public static void downloadPhoto(String path,Load load){
//1.將網址封裝到URL中
URL url=null;
InputStream input=null;
HttpURLConnection conn=null;
try {
url=new URL(path);
conn=(HttpURLConnection) url.openConnection(); //獲取網絡連接對象
conn.connect();//開啟網絡連接
input=conn.getInputStream();//獲取網絡輸入流
ByteArrayOutputStream bos=new ByteArrayOutputStream();
int len=0;
byte[] b=new byte[1024];
while((len=input.read(b))!=-1){
bos.write(b, 0, len);
}
//將下載的數據轉換成字節數組
byte[] date= bos.toByteArray();
load.load(date); //回調load方法
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
測試下載類(主方法):
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[] args) {
String path="http://static.qyer.com/upload/mobile/operation/6e/e1/6ee105f770fe63f625422912b1465e2e.jpg";
//調用下載方法
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("圖片下載成功。。");
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
}
運行結果:
Java學習總結(隨筆)——利用JSON解析實現網絡下載