import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class Utils { //封裝成一個工具類用來下載數據 public static byte[] download(String path){ try { URL url=new URL(path); HttpURLConnection connection=(HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); int code=connection.getResponseCode();//200 if(code==HttpURLConnection.HTTP_OK);{ // 讀取流。 InputStream is=connection.getInputStream(); //內存流 ByteArrayOutputStream bos=new ByteArrayOutputStream(); byte[]a=new byte[1024]; int len=-1; while((len=is.read(a))!=-1){ bos.write(a, 0, len); } is.close(); return bos.toByteArray(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } // 將指定網址的圖片下載,而且寫到文件中,文件名跟網絡上的名字同樣。 public static void writeToFile(String path,String desPath){ //創建一個數組接收在服務器傳過來的數據 byte[]a=download(path); if(a!=null){ String fileName=path.substring(path.lastIndexOf('/')); File file=new File(desPath,fileName); FileOutputStream fos; try { fos = new FileOutputStream(file);//注意這裏沒有判斷文件夾不存在的狀況,若是文件夾不在會出現錯誤 fos.write(a); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } // 根據網址獲得json字符串。 public static String getJson(String path) { byte[] b = download(path); String str = null; try { if (b != null) str = new String(b, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return str; } }