httpclient 上傳檔案、下載檔案

來源:互聯網
上載者:User

標籤:des   style   http   color   java   os   io   strong   

用httpclient4.3 post方式推送檔案到服務端  
準備:httpclient-4.3.3.jar;httpcore-4.3.2.jar;httpmime-4.3.3.jar

標籤: <無>

程式碼片段(1)[全屏查看所有代碼] 1. [代碼][Java]代碼     


/** * 上傳檔案 * @throws  ParseException * @throws  IOException */   publicstaticvoidpostFile()throwsParseException, IOException{    CloseableHttpClient httpClient = HttpClients.createDefault();    try{        // 要上傳的檔案的路徑        String filePath =newString("F:/pic/001.jpg");        // 把一個普通參數和檔案上傳給下面這個地址 是一個servlet        HttpPost httpPost =newHttpPost(                "http://localhost:8080/xxx/xxx.action");        // 把檔案轉換成流對象FileBody        File file =newFile(filePath);        FileBody bin =newFileBody(file);         StringBody uploadFileName =newStringBody(                "把我修改成檔案名稱", ContentType.create(                        "text/plain", Consts.UTF_8));        //以瀏覽器安全色模式運行,防止檔案名稱亂碼。            HttpEntity reqEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)                .addPart("uploadFile", bin)//uploadFile對應服務端類的同名屬性<File類型>                .addPart("uploadFileName", uploadFileName)//uploadFileName對應服務端類的同名屬性<String類型>                .setCharset(CharsetUtils.get("UTF-8")).build();         httpPost.setEntity(reqEntity);         System.out.println("發起請求的頁面地址 "+ httpPost.getRequestLine());        // 發起請求 並返回請求的響應        CloseableHttpResponse response = httpClient.execute(httpPost);        try{            System.out.println("----------------------------------------");            // 列印響應狀態            System.out.println(response.getStatusLine());            // 擷取響應對象            HttpEntity resEntity = response.getEntity();            if(resEntity !=null) {                // 列印響應長度                System.out.println("Response content length: "                        + resEntity.getContentLength());                // 列印響應內容                System.out.println(EntityUtils.toString(resEntity,                        Charset.forName("UTF-8")));            }            // 銷毀            EntityUtils.consume(resEntity);        }finally{            response.close();        }    }finally{        httpClient.close();    }}  /** * 下載檔案 * @param  url * @param  destFileName   xxx.jpg/xxx.png/xxx.txt * @throws  ClientProtocolException * @throws IOException */publicstaticvoidgetFile(String url, String destFileName)        throwsClientProtocolException, IOException {    // 產生一個httpclient對象    CloseableHttpClient httpclient = HttpClients.createDefault();    HttpGet httpget =newHttpGet(url);    HttpResponse response = httpclient.execute(httpget);    HttpEntity entity = response.getEntity();    InputStream in = entity.getContent();    File file =newFile(destFileName);    try{        FileOutputStream fout =newFileOutputStream(file);        intl = -1;        byte[] tmp =newbyte[1024];        while((l = in.read(tmp)) != -1) {            fout.write(tmp,0, l);            // 注意這裡如果用OutputStream.write(buff)的話,圖片會失真,大家可以試試        }        fout.flush();        fout.close();    }finally{        // 關閉低層流。        in.close();    }    httpclient.close();}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.