Retrofit上传文件

依赖:
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,用于封装构建RequestBody
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);

// MultipartBody.Part  和后端约定好Key,这里的partName是用image
MultipartBody.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();
            }
        });
    }
});

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值