Android 通過httppost上傳文字檔到伺服器。

來源:互聯網
上載者:User

標籤:

/**     * 往伺服器上上傳文本  比如log日誌     * @param urlstr        請求的url        * @param uploadFile    log日誌的路徑       *                                    /mnt/shell/emulated/0/LOG/LOG.log         * @param newName        log日誌的名字 LOG.log     * @return     */    public static void httpPost(Activity activity,String urlstr,String uploadFile,String newName) {        LogUtil.info("getEhttpPostt", "urlstr="+urlstr+";uploadFile="+uploadFile+";newName="+newName,"i");        String end = "\r\n";        String twoHyphens = "--";        String boundary = "*****";//邊界標識         int TIME_OUT = 10*1000;   //逾時時間        HttpURLConnection con = null;         DataOutputStream ds = null;         InputStream is = null;        try {            URL url = new URL(urlstr);            con = (HttpURLConnection) url.openConnection();            con.setReadTimeout(TIME_OUT);            con.setConnectTimeout(TIME_OUT);            /* 允許Input、Output,不使用Cache */            con.setDoInput(true);            con.setDoOutput(true);            con.setUseCaches(false);             // 設定http串連屬性            con.setRequestMethod("POST");//請求方式            con.setRequestProperty("Connection", "Keep-Alive");//在一次TCP串連中可以持續發送多份資料而不會中斷連線            con.setRequestProperty("Charset", "UTF-8");//設定編碼            con.setRequestProperty("Content-Type",//multipart/form-data能上傳檔案的編碼格式                    "multipart/form-data;boundary=" + boundary);             ds = new DataOutputStream(con.getOutputStream());            ds.writeBytes(twoHyphens + boundary + end);            ds.writeBytes("Content-Disposition: form-data; "                    + "name=\"stblog\";filename=\"" + newName + "\"" + end);            ds.writeBytes(end);             // 取得檔案的FileInputStream            FileInputStream fStream = new FileInputStream(uploadFile);            /* 設定每次寫入1024bytes */            int bufferSize = 1024;            byte[] buffer = new byte[bufferSize];            int length = -1;            /* 從檔案讀取資料至緩衝區 */            while ((length = fStream.read(buffer)) != -1) {                /* 將資料寫入DataOutputStream中 */                ds.write(buffer, 0, length);            }            ds.writeBytes(end);            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);//結束             fStream.close();            ds.flush();            /* 取得Response內容 */            is = con.getInputStream();            int ch;            StringBuffer b = new StringBuffer();            while ((ch = is.read()) != -1) {                b.append((char) ch);            }            /* 將Response顯示於Dialog */            showDialog(activity,true,uploadFile,"上傳成功" + b.toString().trim());        } catch (Exception e) {            showDialog(activity,false,uploadFile,"上傳失敗" + e);        }finally {             /* 關閉DataOutputStream */            if(ds!=null){                try {                 ds.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            if (is != null) {                try {                    is.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            if (con != null) {                con.disconnect();            }        }    }    /* 顯示Dialog的method */    private static void showDialog(final Activity activity,final Boolean isSuccess,final String uploadFile,final String mess) {        activity.runOnUiThread(new Runnable() {            @Override            public void run() {                new AlertDialog.Builder(activity).setTitle("Message")                .setMessage(mess)                .setNegativeButton("確定", new DialogInterface.OnClickListener() {                    public void onClick(DialogInterface dialog, int which) {                        File file = new File(uploadFile);                        if(file.exists()&&isSuccess){//記錄檔存在且上傳日誌成功                            file.delete();                            Toast.makeText(activity, "log日誌已刪除", Toast.LENGTH_SHORT).show();                        }                    }                }).show();            }        });            }

 

Android 通過httppost上傳文字檔到伺服器。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.