Retrofit上传头像

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://120.27.23.105/")//网址
        .addConverterFactory(GsonConverterFactory.create())//Gson工厂类
        .build();
GitHubApi api = retrofit.create(GitHubApi.class);// 自定义接口对象
//创建文件对象,传入文件地址
File file = new File("/storage/emulated/0/Pictures/Screenshots/a.jpg");
System.out.println("文件路径为:"+file.getAbsolutePath());
// 将文件对象传入RequestBody对象中
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
// 将RequestBody对象传入MultipartBody对象中(1.后台需要的key类型 2.文件名称 3.存有文件对象的RequestBody对象)
MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
// 文件描述对象
final RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), "这是文件描述");
api.upLoading(requestBody,body,"313").enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) {
        System.out.println(response.body().getMsg()+"------------");
    }

    @Override
    public void onFailure(Call call, Throwable t) {

    }

});

接口类:

@Multipart
@POST("file/upload")
Call upLoading(@Part("description") RequestBody description, @Part MultipartBody.Part file,@Query("uid") String uid);
 
  
导入依赖:
 
  
compile 'com.squareup.retrofit2:retrofit:2.0.1'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'


你可能感兴趣的:(Retrofit上传头像)