AndroidTools:網絡工具--基於HTTP上傳數據

AndroidTools Git地址: https://github.com/wisesun7/AndroidTools.git

    本篇通過HTTP的POST方式將數據上傳到服務器中,需要的參數爲URL(服務器地址),data(需上傳的數據)。 這裏簡單介紹一下設置的一些屬性:

  • setRequsetMethod: 設置請求方式,GET和POST兩種,上傳一般使用POST,GET會有明文;
  • setDoInput/Output : 使URL 連接可用於輸入和/或輸出;
  • setConnectTimeout:設置連接超時時間;
  • setRequestProperty: “Content-Type“是設置訪問數據類型,"application/octet-stream"是指以流的形式傳輸,可以是任意類型,詳細可參考http://tool.oschina.net/commons,其中標註了HTML的各種類型;

     另外,流和鏈接的關閉最好放在finally中,這樣防止出現異常時的內存泄漏。

/**
     * @param url : 服務器地址
     * @param data : 上傳的數據
     * @throws IOException
     */
    private void uploadData(String url, byte[] data) throws IOException {
        Log.d(TAG,"upload: " + url + ", length = " + data.length);
        HttpURLConnection connection = null;
        DataOutputStream out = null;

        try {
            connection = (HttpURLConnection)(new URL(url)).openConnection();
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setConnectTimeout(6000);
            connection.setReadTimeout(6000);
            connection.setRequestProperty("Content-Type", "application/octet-stream");
            connection.connect();
            out = new DataOutputStream(connection.getOutputStream());
            out.write(data);
            out.flush();
            int responseCode = connection.getResponseCode();
            Log.d(TAG,url + " RESPONSE " + responseCode);
            if(responseCode != 200) {
                throw new IOException("Response code: " + responseCode);
            }
        } finally {

            if (out != null){
                out.close();
            }
            if(connection != null) {
                connection.disconnect();
            }

        }

    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章