Okhttp3的requestbody的笔记

contentType详解

http协议详解

一、

1、Content-Type的格式:
Content-Type:type/subtype ;parameter

    type:主类型,任意的字符串,如text,如果是*号代表所有;
    subtype:子类型,任意的字符串,如html,如果是*号代表所有,用“/”与主类型隔开;
    parameter:可选参数,如charset,boundary等。

2、RequestBody的数据格式都要指定Content-Type,常见的有三种:

  • application/x-www-form-urlencoded 数据是个普通表单

  • multipart/form-data 数据里有文件

  • application/json 数据是个json

二、
1、RequestBody body = new FormBody.Builder()
    .add("键", "值")
    .add("键", "值")
    ...
    .build();
上面测创建,并没有指定Content-Type,因为FormBody继承了RequestBody,它已经指定了数据类型为application/x-www-form-urlencoded。

2、如果表单是个json:

MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, "你的json");

3、如果数据包含文件:

RequestBody requestBody = new MultipartBody.Builder()
    .setType(MultipartBody.FORM)
    .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file))
    .build();

三、示例

1、提交文件:

        MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
        OkHttpClient okHttpClient = new OkHttpClient();
        //构建指定文件实例
        File file = new File("/storage/emulated/0/test.txt");
        Request request = new Request.Builder()
                .url("https://api.github.com/markdown/raw")
                //传入文件实例
                .post(RequestBody.create(mediaType, file))
                .build();
        Call call=okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                GyLog.d( "onFailure: " + e.getMessage());
            }
 
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                GyLog.d(" response.body() = "+response.body().string());
                GyLog.d(" response.code() = "+response.code());
                GyLog.d(" response.message() = "+response.message());
            }
        });

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值