1. 程式人生 > >MultipartBody uploadFile 本地上傳

MultipartBody uploadFile 本地上傳

/**
 * post方式二:stirng型別引數和上傳檔案引數
 */
public void uploadFile(Map<String, Object> params) {//標註 集合必須包含 url 
    //post請求方式二:multipart/form-data(不僅能夠上傳string型別的引數,還可以上傳檔案(流的形式,file))
OkHttpClient okHttpClient1 = new OkHttpClient();//推薦使用多執行緒
MultipartBody.Builder builder1 = new MultipartBody.Builder();//構建者模式
builder1.setType(MultipartBody.FORM);//傳輸型別 for (Map.Entry<String, Object> stringObjectEntry : params.entrySet()) {//沒有判空 String key = stringObjectEntry.getKey(); Object value = stringObjectEntry.getValue(); if (value instanceof File) {//如果請求的值是檔案 File file = (File) value; //MediaType.parse("application/octet-stream")以二進位制的形式上傳檔案
builder1.addFormDataPart("jokeFiles", ((File) value).getName(), RequestBody.create(MediaType.parse("application/octet-stream"), file)); } else {//如果請求的值是string型別 if(!"url".equals(key)){ builder1.addFormDataPart(key, value.toString()); } } } //進行請求 Request request1 = new
Request.Builder().post(builder1.build()).url((String) params.get("url")).build(); okHttpClient1.newCall(request1).enqueue(new Callback() { @Override public void onFailure(okhttp3.Call call, IOException e) { } @Override public void onResponse(okhttp3.Call call, Response response) throws IOException { if (response.isSuccessful()){//200-300 } } });