Android必知必會-使用okhttp的PUT方式上傳檔案

來源:互聯網
上載者:User

Android必知必會-使用okhttp的PUT方式上傳檔案
背景

公司的檔案上傳介面使用PUT協議,之前一直用的都是老項目中的上傳類,現在項目中使用了okhttp網路程式庫,就查了下資料,在這裡分享一下。

代碼實現
    /**     * @param mediaType MediaType     * @param uploadUrl put請求地址     * @param localPath 本地檔案路徑     * @return 響應的結果 和 HTTP status code     * @throws IOException     */    public String put(MediaType mediaType, String uploadUrl, String localPath) throws IOException {        File file = new File(localPath);        RequestBody body = RequestBody.create(mediaType, file);        Request request = new Request.Builder()                .url(uploadUrl)                .put(body)                .build();        Response response = client.newCall(request).execute();        return response.code()+ ":" + response.body().string() ;    }    //上傳JPG圖片    public String putImg(String uploadUrl, String localPath) throws IOException {        MediaType Image = MediaType.parse("image/jpeg; charset=utf-8");        return put(Image, uploadUrl, localPath);    }

可能還需要進行的設定:修改各種Timeout

OkHttpClient client = new OkHttpClient();client.setConnectTimeout(30, TimeUnit.SECONDS);client.setReadTimeout(15, TimeUnit.SECONDS);client.setWriteTimeout(30, TimeUnit.SECONDS);

PS:以上代碼基於okhttp-2.7.2,其他版本未測試,理論上是通用的。

總結

以上是最基本的代碼實現,你還可以加上自己的各種監聽。

聯繫我們

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