Retroifit向服务器post请求上传数据

post请求上传json,文件,多张图片

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.btn_post_key_value)
    Button btnPostKeyValue;
    @BindView(R.id.btn_post_map_key_value)
    Button btnPostMapKeyValue;
    @BindView(R.id.btn_post_json)
    Button btnPostJson;
    @BindView(R.id.btn_post_file)
    Button btnPostFile;
    @BindView(R.id.btn_post_files)
    Button btnPostFiles;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    @OnClick({R.id.btn_post_key_value, R.id.btn_post_map_key_value, R.id.btn_post_json, R.id.btn_post_file, R.id.btn_post_files})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_post_key_value:
                postKeyValue();
                break;
            case R.id.btn_post_map_key_value:
                postKeyValueMap();
                break;
            case R.id.btn_post_json:
                postJson();
                break;
            case R.id.btn_post_file:
                postFile();
                break;
            case R.id.btn_post_files:
                postFiles();
                break;
        }
    }

    private void postFiles() {

        try {
            //准备好需要上传给服务器的文件
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.a);
            File imgFile = new File(getCacheDir(), "imgFile");
            FileOutputStream fileOutputStream = null;
            fileOutputStream = new FileOutputStream(imgFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,fileOutputStream);

            Bitmap bitmap1 = BitmapFactory.decodeResource(getResources(), R.mipmap.b);
            File imgFile1 = new File(getCacheDir(), "imgFile");
            FileOutputStream fileOutputStream1 = null;
            fileOutputStream1 = new FileOutputStream(imgFile1);
            bitmap1.compress(Bitmap.CompressFormat.JPEG,100,fileOutputStream1);

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("http://httpbin.org/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            ResponseInfoApi responseInfoApi = retrofit.create(ResponseInfoApi.class);

            // 创建 RequestBody,用于封装构建RequestBody
            RequestBody requestFile =
                    RequestBody.create(MediaType.parse("multipart/form-data"),imgFile);
            RequestBody requestFile1 =
                    RequestBody.create(MediaType.parse("multipart/form-data"),imgFile1);

            HashMap<String, RequestBody> map = new HashMap<>();
            map.put("actimg",requestFile);
            map.put("listImg",requestFile1);

            Call<ResponseBody> call = responseInfoApi.uploadFiles(map);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    ResponseBody body = response.body();
                    Log.i("","请求成功");
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    Log.i("","请求失败");
                }
            });
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

    private void postFile() {
        try {
            //准备好需要上传给服务器的文件
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
            File imgFile = new File(getCacheDir(), "imgFile");
            FileOutputStream fileOutputStream = new FileOutputStream(imgFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,fileOutputStream);

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("http://httpbin.org/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            ResponseInfoApi responseInfoApi = retrofit.create(ResponseInfoApi.class);


            // 创建 RequestBody,用于封装构建RequestBody
            RequestBody requestFile =
                    RequestBody.create(MediaType.parse("multipart/form-data"),imgFile);
            // MultipartBody.Part和后端约定好Key,这里的partName是用actimg
            // 上传文件名称
            //  需要上传文件所在的RequestBody对象
            MultipartBody.Part body =
                    MultipartBody.Part.createFormData("actimg", imgFile.getName(), requestFile);

            Call<ResponseBody> call = responseInfoApi.upload(body);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    ResponseBody responseBody = response.body();
                    Log.i("","上传成功");
                }
                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    Log.i("","上传失败");

                }
            });
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void postJson() {
        Student student = new Student("张小龙", "20");
        Gson gson = new Gson();
        String json = gson.toJson(student);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://httpbin.org/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        ResponseInfoApi responseInfoApi = retrofit.create(ResponseInfoApi.class);

        //postJson方法用于传递json给服务器,需要指定一个请求体RequestBody
        RequestBody requestBody = RequestBody.create(
                MediaType.parse("application/json; charset=utf-8"), json);

        Call<ResponseBody> call = responseInfoApi.postJson(requestBody);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    ResponseBody body = response.body();
                    Log.i("","body.string() = "+body.string());
                    Log.i("","请求成功");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i("","请求失败");
            }
        });
    }

    private void postKeyValueMap() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("name","张小龙");
        hashMap.put("age","19");

        //发送一个post请求给指定链接地址  baseurl  :  http://httpbin.org/    后半部分用于测试post请求链接地址:post
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://httpbin.org/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        ResponseInfoApi responseInfoApi = retrofit.create(ResponseInfoApi.class);
        //将请求的数据封装在map集合中上传给服务器
        Call<ResponseBody> call = responseInfoApi.postKeyValueMap(hashMap);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    //获取服务器返回的响应体
                    ResponseBody body = response.body();
                    //服务器返回的字符串获取下来
                    Log.i("","body.string() = "+body.string());
                    Log.i("","请求成功");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i("","请求失败");

            }
        });
    }

    private void postKeyValue() {
        //发送一个post请求给指定链接地址  baseurl  :  http://httpbin.org/    后半部分用于测试post请求链接地址:post
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://httpbin.org/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        ResponseInfoApi responseInfoApi = retrofit.create(ResponseInfoApi.class);
        Call<ResponseBody> call = responseInfoApi.postKeyValue("张小龙", "18");
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    //获取服务器返回的响应体
                    ResponseBody body = response.body();
                    //服务器返回的字符串获取下来
                    Log.i("","body.string() = "+body.string());
                    Log.i("","请求成功");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i("","请求失败");

            }
        });
    }

    public interface ResponseInfoApi{
        //响应体  http://httpbin.org/post?name=""&age=""
        //表单发送数据给服务器
        @FormUrlEncoded()
        @POST("post")
        Call<ResponseBody> postKeyValue(@Field("name") String name,@Field("age") String age);

        @FormUrlEncoded()
        @POST("post")
        Call<ResponseBody> postKeyValueMap(@FieldMap() Map<String,String> map);
        //发送请求的时候,将键值对封装在一个map集中进行上传

        //post请求上传json
        //Content-Type 代表数据类型
        //accept 告知服务器接收数据类型
        //RequestBody 代表请求体
        //ResponseBody 代表响应体
        @Headers({"Content-Type: application/json","Accept: application/json"})
        @POST("post")
        Call<ResponseBody> postJson(@Body RequestBody body);


        //post请求上传文件
        //@Multipart  多部件,代表需要上传文件
        //MultipartBody.Part 包含文件的对象
        @Multipart
        @POST("post")
        Call<ResponseBody> upload(@Part MultipartBody.Part file);

        //post请求上传多张图片
        @Multipart
        @POST("post")
        Call<ResponseBody> uploadFiles(
                @PartMap() Map<String, RequestBody> maps);
    }
}

javaBean

public class Student {
    private String name;
    private String age;

    public Student(String name, String age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值