android網絡編程之HttpUrlConnection的講解--上傳大文件


1、服務器后台使用Servlet開發,這里不再介紹。

2、網絡開發不要忘記在配置文件中添加訪問網絡的權限

<uses-permission android:name="android.permission.INTERNET"/>

3、網絡請求、處理不能在主線程中進行,一定要在子線程中進行。因為網絡請求一般有1~3秒左右的延時,在主線程中進行造成主線程的停頓,對用戶體驗來說是致命的。(主線程應該只進行UI繪制,像網絡請求、資源下載、各種耗時操作都應該放到子線程中)。

4、傳輸大文件的時候會出現OOM出錯,所以我們可以設置每次傳輸流的大小。

5、

public class FileActivity extends Activity {
    private TextView mTvMsg;
    
    private String result = null;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_file);
        
        initView();
    }
    
    private void initView(){
        mTvMsg = (TextView) findViewById(R.id.tv_msg);
        
        new Thread(fileThread).start();
    }
    
    private Thread fileThread = new Thread(){
        public void run() {
            HttpURLConnection connection = null;
            try {
                URL url = new URL("http://192.168.23.1:8080/TestProject/FileTest");
                connection = (HttpURLConnection) url.openConnection();
                // 設置每次傳輸的流大小,可以有效防止手機因為內存不足崩潰
                // 此方法用於在預先不知道內容長度時啟用沒有進行內部緩沖的 HTTP請求正文的流。
                connection.setChunkedStreamingMode(51200); // 128K
                // 不使用緩存
                connection.setUseCaches(false);
                // 設置請求方式
                connection.setRequestMethod("POST");
                // 設置編碼格式
                connection.setRequestProperty("Charset", "UTF-8");
                // 設置容許輸出
                connection.setDoOutput(true);

                // 上傳文件
                FileInputStream file = new FileInputStream(Environment.getExternalStorageDirectory().getPath() 
                        + "/aaaaa/baidu_map.apk");
                OutputStream os = connection.getOutputStream();
                byte[] b = new byte[1024];
                int count = 0;
                while((count = file.read(b)) != -1){
                    os.write(b, 0, count);
                }
                os.flush();
                os.close();
                
                // 獲取返回數據
                if(connection.getResponseCode() == 200){
                    InputStream is = connection.getInputStream();
                    result = StringStreamUtil.inputStreamToString(is);
                    
                    Message msg = Message.obtain();
                    msg.what = 0;
                    fileHandler.sendMessage(msg);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if(connection != null){
                    connection.disconnect();
                }
            }
        };
    };
    
    private Handler fileHandler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            if(msg.what == 0 && result!=null){
                mTvMsg.setText(result);
            }
        };
    };
}

6、輸出流OutputStream的三個方法,第二和第三個方法應該是安全的,但第一個方法可能出現錯誤。因為你沒讀1024字節,卻寫了1024字節,所以可能出錯。(我試了幾次是出錯的,也可能是我代碼寫錯了,但我建議大家還是不要使用第一個方法)。

    os.write(byte[] buffer);
    os.write(int arg0);
    os.write(byte[] buffer, int offset, int count);

7、android HttpURLConnection上傳文件出現Content-Length的長度限制參考博文:

     http://www.oschina.net/question/223455_44878

8、android 上傳大文件中斷參考博文:

     http://www.oschina.net/question/94349_58751


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM