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,其他版本未測試,理論上是通用的。
總結
以上是最基本的代碼實現,你還可以加上自己的各種監聽。