Retrofit上传文件

来源:互联网 发布:淘宝商城铂金会员 编辑:程序博客网 时间:2024/06/06 07:08
依赖:
compile 'com.squareup.retrofit2:converter-gson:2.0.1'

compile 'com.squareup.retrofit2:retrofit:2.0.1'

接口:

public interface setData {    @Multipart    @POST()    Call<ResponseBody> upload(@Url String url, @Query("uid") int uid, @Part MultipartBody.Part file);}

主Activity:

Retrofit retrofit = new Retrofit.Builder().baseUrl("https://www.zhaoapi.cn/").addConverterFactory(GsonConverterFactory.create())        //.client(okHttpClient)        .build();System.out.println("*************");Head head = retrofit.create(Head.class);File file = new File(Environment.getExternalStorageDirectory(),"b.jpg");// 创建 RequestBody,用于封装构建RequestBodyRequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);// MultipartBody.Part  和后端约定好Key,这里的partName是用imageMultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);Call<ResponseBody> sethead = head.upload("https://www.zhaoapi.cn/file/upload", 86, body);sethead.enqueue(new Callback<ResponseBody>() {    @Override    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {        try {            final String string = response.body().string();            System.out.println("****+++成功+++****"+string);            runOnUiThread(new Runnable() {                @Override                public void run() {                    Toast.makeText(MainActivity.this, string+"", Toast.LENGTH_SHORT).show();                }            });        } catch (IOException e) {            e.printStackTrace();        }    }    @Override    public void onFailure(Call<ResponseBody> call, final Throwable t) {        System.out.println("***--失败--***" + t.toString());        runOnUiThread(new Runnable() {            @Override            public void run() {                Toast.makeText(MainActivity.this, t.toString()+"", Toast.LENGTH_SHORT).show();            }        });    }});

原创粉丝点击