1. 程式人生 > >HttpURLConnection下載網路檔案,載入網路圖片

HttpURLConnection下載網路檔案,載入網路圖片

說明:

做sdk開發的時候(sdk不採取任何第三方框架),涉及到下載網路檔案,和載入網路圖片的功能,由於不能用第三方jar包進行,所以只能用基本的HttpURLConnection把檔案作為流來處理,進行下載和載入。

1、HttpURLConnection載入圖片

程式碼:

 /**
     * 載入圖片ImageView
     * @param url 圖片網路地址
     * @return
     */
    public void setImageViewBitMap(ImageView imageView, final String url) {
        this.imageView = imageView;

        new Thread() {
            @Override
            public void run() {
                URL myFileUrl = null;
                Bitmap bitmap = null;
                try {
                    myFileUrl = new URL(url);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                try {
                    HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                imageBitmap = bitmap;
                myHandler.sendEmptyMessage(1);
            }
        }.start();
    }

2、HttpURLConnection下載檔案

程式碼:

/**
     * 把js,css儲存在本地
     * @param uFile 本地儲存的檔名File路徑
     * @param url 將要下載的js,css檔案
     */ 
    public static void writeUrToStrealm(File uFile, String url) {
        try {
            URL uri = new URL(url);
            URLConnection connection = uri.openConnection();
            InputStream uristream = connection.getInputStream();
            //String cache = connection.getHeaderField("Ddbuild-Cache");
            String contentType = connection.getContentType();
            //textml; charset=utf-8
            String mimeType = "";
            String encoding = "";
            if (contentType != null && !"".equals(contentType)) {
                if (contentType.indexOf(";") != -1) {
                    String[] args = contentType.split(";");
                    mimeType = args[0];
                    String[] args2 = args[1].trim().split("=");
                    if (args.length == 2 && args2[0].trim().toLowerCase().equals("charset")) {
                        encoding = args2[1].trim();
                    } else {

                        encoding = "utf-8";
                    }
                } else {
                    mimeType = contentType;
                    encoding = "utf-8";
                }
            }

            //todo:快取uristream
            FileOutputStream output = new FileOutputStream(uFile);
            int read_len;
            byte[] buffer = new byte[1024];

            SaveDataUtils.writeBlock(output, mimeType);
            SaveDataUtils.writeBlock(output, encoding);
            while ((read_len = uristream.read(buffer)) > 0) {
                output.write(buffer, 0, read_len);
            }
            output.close();
            uristream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


相關推薦

HttpURLConnection下載網路檔案載入網路圖片

說明: 做sdk開發的時候(sdk不採取任何第三方框架),涉及到下載網路檔案,和載入網路圖片的功能,由於不能用第三方jar包進行,所以只能用基本的HttpURLConnection把檔案作為流來處理,進行下載和載入。 1、HttpURLConnection載入圖片 程

ssl證書安裝完後https訪問後下載index檔案HTTP訪問正常的。Nginx ssl設定後自動下載根目錄的index.php而不是載入

給Nginx安裝ssl證書,https訪問後,重新自動下載index.php檔案。一開始的Nginx的配置檔案如下: #user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.

C#開發的定時自動拷貝檔案到別處並刪除過期備份檔案支援網路上的芳鄰拷貝

開發工具VS2013  .net 框架 2.0 SQL server的備份檔案只可以備份在本機,只有一份,這個軟體可以定時把備份檔案拷貝到別的機器,作為另外的備份,還可以在成功備份後自動刪除過期的檔案,沒有成功備份,不刪除過期檔案,以免誤刪,除非手動刪除。 拷貝檔案過程中沒有進度條

利用keras載入訓練好的.H5檔案並預測圖片

import matplotlib matplotlib.use('Agg') import os from keras.models import load_model import numpy as np from PIL import Image import cv2

httpurlconnection下載pdf檔案打不開的原因和解決程式碼

前幾天遇見一個問題,httpurlconnection傳送請求下載pdf檔案的時候,檔案是下載下來了,但是打不開。 之前並沒有對pdf操作的相關功能,所以一直是使用的字元流讀取內容。 字元流主要針對一些文字文件(比位元組流操作的效率要高),比如.txt、.doc,而pdf就不行。 位元組流幾乎可

解析本地json檔案模擬網路請求

/** * Demo class * * @author yyd * @date 2017/11/15 */ public class ParseLocalJsonUtil { /** * 從asset路徑下讀取對應檔案轉String輸出 * <p&

網路中獲取載入一個圖片

import java.io.BufferedInputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection;

springmvc下載excel檔案通過get方式傳少量引數

Html <el-button @click=downloadExcel>資料匯出</el-button> export default { methods:{ downloadExcel(){ window.location.href='/api

Java編寫爬蟲並儲存本地檔案未涉及圖片視訊的儲存只是儲存文字內容

Java Jsoup jar包編寫爬蟲 這個案例內容很簡單,只是設計文字的爬取,未涉及到圖片儲存與視訊儲存。記錄下來只是方便自己的一個記錄、同時希望給向我這樣第一次接觸爬蟲的朋友一個參考!! 個人覺得分為兩步走!當然,我寫了三個檔案,內容如下: 一、開始方法 S

servlet解決get請求方式下載中文檔案檔名稱丟失問題

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filenam

linux c 網路程式設計 常用網路函式範例

hstrerror返回網路錯誤原因的描述字串相關函式:herror表頭檔案:#include <netdb.h>函式定義:const char *hstrerror(int err)函式說明:hstrerror()用來依引數err的錯誤程式碼來查詢socket錯誤原因的描述字串, 然後將該字串指標

網頁JS下載檔案並改檔名

1、使用加入多個iframe方法,開啟多個連結function _createIFrame(url, triggerDelay, removeDelay) { setTimeout(() => { let frame = document.cre

Linux從Ftp上下載最新檔案並儲存到指定目錄(實現有點2--)

#!/bin/bash #PS4="#:" #set -x ip=a.b.c.d user=*** passwd=*** srcdir=~/Game ftp -n << ! open $ip 21 user $user $passwd prompt binary dir /server/Linux

tensorflow 生成.pb檔案載入.pb檔案---遷移學習

這篇薄荷主要是講了如何用tensorflow去訓練好一個模型,然後生成相應的pb檔案。最後會將如何重新載入這個pb檔案。 train 首先說一下train。一開始當然是讀圖片啦。 用io.imread來讀取每一張圖片,然後resize成vgg的輸入的大小

Unity3D-動態讀取配置檔案載入遊戲物件

private Dictionary<int,T> LoadConfig<T>(string fileName) where T : class,new() {

js 下載pdf檔案而不是開啟預覽 方案

專案需求 常規加上download 屬性 <a href="https://testmv.xesimg.com/ExpCourse/image/2018/10/09/15390717545791

Keil 下載HEX檔案無需原始碼。

一.準備工具 1.安裝好的Keil,如果是keil5需要有準備下載的晶片的PACK。 2.下載器,推薦U-LINK。 3.準備下載的hex檔案。 二.開始 1.首先開啟Keil,新建一個新的工程,選擇你需要的晶片,不

Unity載入網路圖片並顯示在UGUI上解決載入網路圖片出現問號的問題及其案例分析例項Demo親測可用

Unity載入網路圖片並顯示在UGUI上,解決載入網路圖片出現問號的問題及其案例分析,例項Demo親測可用 最近自己在載入網路圖片的時候也遇到了載入的圖片無法顯示或者是問號的問題。下面就分析下為什麼會出現這樣的情況。   首先我們直接上程式碼(比較簡單) using U

XListView重新整理載入多條目網路資料網路載入圖片

MainActivity.java protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setConte

Tensorflow訓練卷積神經網路並儲存模型載入模型並匯入手寫圖片測試

        剛學習tensorflow,折騰了這幾天,之前一直按照書上的教程訓練網路,看那些沒玩沒了的不斷接近於1的準確率,甚是無聊,我一直想將辛辛苦苦訓練出來的網路,那些識別率看上去很高的網路,是否能真正用來識別外面匯入的圖片呢,而不僅僅是那些訓練集或者測試集的圖片。