框架代码就不粘了 1.Retrofit+Rxjava Utils类关键代码 File f1 = new File("/storage/emulated/0/Pictures/c.png"); RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), f1); // MultipartBody.Part 和后端约定好Key,这里的partName是用image MultipartBody.Part body = MultipartBody.Part.createFormData("image", f1.getName(), requestFile); RequestBody uidBody = RequestBody.create(MediaType.parse("text/plain"), uid); Api关键代码
@POST(UPLOAD_PATH) @Multipart Flowable<Bean> upLoad(@Part("uid") RequestBody uid, @Part MultipartBody.Part file);2.okhttp
FormBody paramsBody=new FormBody.Builder() .add("id","id(参数)").build();
MediaType type=MediaType.parse("application/octet-stream");//"text/xml;charset=utf-8" File file=new File("文件路径"); RequestBody fileBody=RequestBody.create(type,file);
RequestBody multipartBody = new MultipartBody.Builder() .setType(MultipartBody. ALTERNATIVE)
//一样的效果 .addPart(Headers.of( "Content-Disposition", "form-data; name=\"params\"") ,paramsBody) .addPart(Headers.of( "Content-Disposition", "form-data; name=\"file\"; filename=\"plans.xml\"") ,fileBody)
Request request= new Request.Builder().url (url) .addHeader( "User-Agent", "android") .header( "Content-Type", "text/html; charset=utf-8;") .post(multipartBody)//传参数、文件或者混合,改一下就行请求体就行 .build();