/** * * @param url 上传文件地址 * @param map 上传的参数 * @param file 上传的文件 * @return * @throws IOException */ public static Response okhttpUpload(final String url, final Map<String, String> map, File file) throws IOException { MultipartBody.Builder builder = new MultipartBody.Builder(); builder.setType(MultipartBody.FORM); if (file != null) { builder.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file)); } if (map != null) { // map 里面是请求中所需要的 key 和 value for (Map.Entry<String, String> entry : map.entrySet()) { builder.addFormDataPart(entry.getKey(), entry.getValue()); } } RequestBody body = builder.build(); Request request = new Request.Builder() .url(url) .post(body) .build(); OkHttpClient okHttpClient = new OkHttpClient(); Response response = okHttpClient.newCall(request).execute(); return response; }
OKHttp文件上传
最新推荐文章于 2024-07-26 11:10:37 发布