Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 上傳圖片與普通參數到服務器:HttpURLConnection 與 Struts2 完整對接實錄

編輯:關於 Android 程式設計

項目做到一半,需求來了:客戶端要能把圖片上傳到後台,而且不能只傳文件,還得捎帶一批普通參數。折騰了好幾天,把踩過的坑和最終方案記錄下來。

為什麼選 HttpURLConnection 而不是 HttpClient

Android 端要和後台通信,繞不開 HTTP。可用的工具主要有兩個:HttpClient(位於 org.apache.http.client 包下)和 HttpURLConnection(java.net 體系,Android 原生自帶)。

兩者都能完成網絡通信,但官方文檔明確表態:新的應用應該優先使用 HttpURLConnection。原因不只是「官方推薦」這麼一句話——Google 在 Android 4.0 之後針對 HttpURLConnection 做了不少優化,包括底層連接複用、對 gzip 壓縮的透明處理以及更合理的緩存策略。而 HttpClient 在 Android 5.1 之後已被標記為 deprecated,5.0 之後更是從平台上移除,需要自行引入外部 jar。

网上的對比測試也大致支持這個結論:傳輸大文件時 HttpURLConnection 略快一籌,而在傳輸少量普通參數時兩者差異不明顯。既然如此,這裡就選 HttpURLConnection 作為實現方案。

Android 客戶端

界面非常樸素,一個選圖按鈕、一個上傳按鈕、一塊顯示結果的文本區域。

整體邏輯分四步:

  1. 點擊「選圖片」,通過 Intent.ACTION_PICK 拉起系統相冊;
  2. 點擊「上傳圖片」,把選中的文件連同普通參數一起發往服務器;
  3. 上傳過程中實時刷新進度;
  4. 上傳結束後,把服務器返回的 JSON 展示出來。

代碼組織上分為四個部分:

  • 界面展示放在 MainActivity 中;
  • ConfigParamters 負責存放 HTTP 請求的公共參數配置;
  • HttpUrlConn 是請求的核心類,承擔拼接報文、寫流、讀響應的全部工作;
  • UploadLinsener 作為監聽器接口,向上回報上傳進度與成功/失敗狀態。

HttpUrlConn 核心代碼

public class HttpUrlConn {

    private String TAG = "HttpUrlConn";

    // HttpURLConnection 請求對象
    private HttpURLConnection myhttpconnect;

    // 分割標記
    private String twoHyphens = "--";
    private String boundary   = "*****";

    // 數據輸出管道
    private DataOutputStream ds = null;

    // 文件上傳監聽
    private UploadLinsener uploadlinsener;

    // 文件總大小 / 當前已傳輸大小
    private double allFilesize = 0;
    private double curr_ret    = 0;

    /**
     * 建立連接並完成上傳
     *
     * @param path      接口地址
     * @param paramString 普通參數
     * @param paramFiles  需要上傳的文件參數
     * @param config    連接公共屬性配置
     */
    public HttpURLConnection getHttpUrlConnInstances(String path,
                                                     HashMap<String, String> paramString,
                                                     HashMap<String, File> paramFiles,
                                                     ConfigParamters config) {
        try {
            URL url = new URL(path);
            myhttpconnect = (HttpURLConnection) url.openConnection();

            /* 允許 Input、Output,post 中不使用 Cache */
            myhttpconnect.setDoInput(config.isDoInput());
            myhttpconnect.setDoOutput(config.isDoOutput());
            myhttpconnect.setUseCaches(config.isUseCaches());

            /* 設置傳輸方式為 POST */
            myhttpconnect.setRequestMethod(config.getUseMethod());

            /* 設置公共請求頭 */
            myhttpconnect.setRequestProperty("Connection", "Keep-Alive");
            myhttpconnect.setRequestProperty("Charset", "UTF-8");
            myhttpconnect.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);

            /* 設置 DataOutputStream */
            ds = new DataOutputStream(myhttpconnect.getOutputStream());

            /* 先把普通參數寫到服務器 */
            if (null != paramString && paramString.size() > 0) {
                writeStringParam(ds, paramString);
            }

            /* 再把文件參數寫到服務器 */
            if (null != paramFiles && paramFiles.size() > 0) {
                writeFileParam(ds, paramFiles);
            }

            // 添加結尾標志
            paramsEnd(ds);

            if (myhttpconnect.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream is = myhttpconnect.getInputStream();
                String successMsg = InputStremtoString(is);
                if (uploadlinsener != null) {
                    uploadlinsener.uploadSucsess(successMsg);
                }
            } else {
                uploadlinsener.uploadFail("錯誤,錯誤碼 ResponseCode:"
                        + myhttpconnect.getResponseCode());
            }
            ds.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
            if (uploadlinsener != null) uploadlinsener.uploadFail(e.toString());
        } catch (IOException e) {
            e.printStackTrace();
            if (uploadlinsener != null) uploadlinsener.uploadFail(e.toString());
        } catch (Exception e) {
            e.printStackTrace();
            if (uploadlinsener != null) uploadlinsener.uploadFail(e.toString());
        }
        return myhttpconnect;
    }

    /** 把字節輸入流轉換成字符串 */
    private String InputStremtoString(InputStream is) throws Exception {
        int ch;
        StringBuffer b = new StringBuffer();
        byte[] bt = new byte[1024];
        while ((ch = is.read(bt)) != -1) {
            b.append(new String(bt, 0, ch, "UTF-8"));
        }
        return b.toString();
    }

    /** 傳普通參數 */
    private void writeStringParam(DataOutputStream ds, HashMap<String, String> params) {
        try {
            Set<String> keySet = params.keySet();
            for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
                String name  = it.next();
                String value = params.get(name);
                ds.writeBytes(twoHyphens + boundary + "\r\n");
                ds.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"\r\n");
                ds.writeBytes("\r\n");
                ds.writeBytes(value + "\r\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** 傳輸文件 */
    private void writeFileParam(DataOutputStream ds, HashMap<String, File> params) {
        try {
            Set<String> keySet = params.keySet();
            getFilesSize(params);
            for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
                String name  = it.next();
                File value   = params.get(name);
                ds.writeBytes(twoHyphens + boundary + "\r\n");
                ds.writeBytes("Content-Disposition: form-data; name=\"" + name
                        + "\"; filename=\"" + URLEncoder.encode(value.getName(), "UTF-8") + "\"\r\n");
                ds.writeBytes("Content-Type: " + getContentType(value) + "\r\n");
                ds.writeBytes("\r\n");
                ds.write(getBytes(value));
                ds.writeBytes("\r\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** 獲取要傳輸文件總共大小 */
    private void getFilesSize(HashMap<String, File> params) {
        for (Entry<String, File> data : params.entrySet()) {
            File f = data.getValue();
            allFilesize += f.length();
        }
        Log.i(TAG, "AllFileSize:" + allFilesize);
    }

    /** 獲取文件上傳類型:圖片為 image/png、image/jpg 等,非圖片為 application/octet-stream */
    private String getContentType(File f) throws Exception {
        return "application/octet-stream";
    }

    /** 添加結尾數據 */
    private void paramsEnd(DataOutputStream ds) throws Exception {
        ds.writeBytes(twoHyphens + boundary + twoHyphens + "\r\n");
        ds.writeBytes("\r\n");
    }

    /** 把文件轉換成字節數組,同時統計上傳進度 */
    private byte[] getBytes(File f) throws Exception {
        FileInputStream in = new FileInputStream(f);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int n;
        while ((n = in.read(b)) != -1) {
            out.write(b, 0, n);
            if (allFilesize > 0) {
                curr_ret += n;
                double level = (curr_ret / allFilesize) * 100;
                if (uploadlinsener != null) {
                    uploadlinsener.uploading(level);
                }
            }
        }
        in.close();
        return out.toByteArray();
    }

    public void setUploadlinsener(UploadLinsener uploadlinsener) {
        this.uploadlinsener = uploadlinsener;
    }
}

各方法職責梳理

  1. getHttpUrlConnInstances():獲取並配置連接,拼接參數發送給服務器,再通過 getInputStream() 讀取響應。
  2. InputStremtoString():把字節流轉為字符串,用來解析服務器返回的 JSON,注意編碼要與服務端一致。
  3. writeStringParam():普通參數寫入。因為我們是在手工模擬 multipart/form-data 表單提交,所以每段數據都要按協議拼接分隔符與 Content-Disposition 頭。
  4. writeFileParam():文件參數寫入。遍歷 HashMap 中的每個文件逐一寫出,順便統計總大小以便計算進度。這裡的 name 必須和服務端約定一致,否則後台取不到。
  5. getFilesSize():統計所有待傳文件的總字節數。
  6. getContentType():判定 MIME 類型,圖片一般返回 image/png、image/jpeg,其餘統一給 application/octet-stream。
  7. paramsEnd():寫入結尾邊界標記,缺少這一步服務端會一直等待報文結束。
  8. getBytes():文件轉字節數組,並在讀取過程中累加已傳字節數回調進度。
  9. setUploadlinsener():注入監聽器,把上傳狀態拋給 UI 層。

另外還有一種更省事的做法:把普通參數直接拼接到 URL 查詢串上(GET 風格),代碼裡我把它註釋保留了下來,作為備選方案。不過一旦參數較多或包含中文,URL 長度和編碼問題會變得麻煩,所以最終還是選擇全部走表單報文。


J2EE 服務端(SSH 框架環境)

後台基於 Struts2 + Spring + Hibernate 搭建,項目搭建過程這裡略過。接收上傳靠的是 Struts2 集成的 Commons FileUpload 組件。

核心邏輯都在 FileUploadAction 裡:

public class FileUploadAction extends ActionSupport {

    public String phoneinfo = "NXJ570";

    public void uploadfielandparam() throws Exception {
        HttpServletRequest request = ServletActionContext.getRequest();
        System.out.println(request.getContentType());
        System.out.println(request.getCharacterEncoding());
        System.out.println(request.getContentLength());

        // 臨時文件夾(tomcat 項目下的 temp)
        String temp = ServletActionContext.getServletContext().getRealPath("/temp");

        // 上傳文件存放位置
        String basepath = ServletActionContext.getServletContext().getRealPath("/myfile");

        HttpServletResponse resp = ServletActionContext.getResponse();

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(10 * 1024 * 1024);   // 單個文件緩存最大值
        factory.setRepository(new File(temp));        // 緩沖區目錄

        // 文件上傳組件(關鍵)
        ServletFileUpload upload1 = new ServletFileUpload(factory);
        upload1.setFileSizeMax(10000000);
        upload1.setSizeMax(480000000);
        upload1.setHeaderEncoding("UTF-8");

        // 開始讀取上傳信息
        int index = 0;
        List<FileItem> fileItems = null;
        try {
            fileItems = upload1.parseRequest(request);
            System.out.println("list = " + fileItems);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Iterator<FileItem> iter = fileItems.iterator();
        // 依次處理每個上傳的表單域
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if (!item.isFormField()) {
                // 文件域
                String name = item.getName();   // 獲取上傳文件名,包括路徑
                name = name.substring(name.lastIndexOf("\\") + 1);
                long size = item.getSize();
                if ((name == null || name.equals("")) && size == 0) continue;

                int point = name.indexOf(".");
                name = (new Date()).getTime() + name.substring(point, name.length());
                index++;

                File fNew = new File(basepath, name);
                try {
                    item.write(fNew);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                // 普通表單字段
                String key = item.getFieldName();
                String fieldvalue = new String(item.getString().getBytes("ISO-8859-1"), "UTF-8");
                System.out.println("params: " + key + "=" + fieldvalue);
            }
        }

        // 把結果封裝成 JSON 返回
        Gson gson = new Gson();
        myobj obj1 = new myobj("0", "seccessed", "服務器已經接收到文件");
        String json = gson.toJson(obj1);
        System.out.println(json);

        // 必須設置編碼,否則客戶端接收到的中文會亂碼
        resp.setContentType("text/html; charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.println(json);
        out.flush();
    }

    // 實體對象
    class myobj {
        private String retcode;
        private String retmessage;
        private String retdata;

        public myobj(String retcode, String retmessage, String retdata) {
            super();
            this.retcode = retcode;
            this.retmessage = retmessage;
            this.retdata = retdata;
        }
        // getter / setter 省略
    }
}

服務端如何拿到普通參數

有兩條路可走。

第一條是傳統方式,直接從 request 上取:

String value = request.getParameter("key");

第二條是從解析出來的 FileItem 列表裡取,因為我們上傳時把所有內容都塞進了同一個 multipart 報文:

// 獲取 key
String key = item.getFieldName();
// 獲取 value,注意編碼轉換
String fieldvalue = new String(item.getString().getBytes("ISO-8859-1"), "UTF-8");

這裡的編碼轉換是關鍵。Tomcat 默認以 ISO-8859-1 解析請求體,如果兩端不做顯式轉碼,中文參數幾乎必然變成亂碼。

調試經驗與遺留問題

速度上確實令人滿意,5MB 的圖片幾秒鐘就傳完了。

關於地址,有幾個細節容易卡住新人:

  • 在 Android 模擬器裡調試時,10.0.2.2 才是宿 localhost 的映射地址,寫成 10.0.0.2 或 127.0.0.1 都找不到服務器;
  • 真機測試則把地址換成電腦在局域網中的實際 IP,並確保手動將 Tomcat 發布上去;
  • 手機與電腦必須處於同一個 WiFi 內網,否則根本路由不到;
  • 如果條件允許,直接部署到公司測試服務器上會省下不少網絡折騰。

項目整體跑通,效果符合預期。唯一還沒徹底解決的問題是:通過表單提交上來的普通參數如果是中文,偶爾仍會出現亂碼。懷疑與 Tomcat 的 server.xml 中 Connector 的 useBodyEncodingForURI 配置以及客戶端 writeBytes 時的編碼處理有關,後續需要再系統排查一次。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved