使用Okhttp执行put空的RequestBody

本文介绍在使用OkHttp发起PUT请求时,如果不需要携带额外参数,如何正确构造请求。通过创建空的RequestBody对象来避免OkHttp强制要求RequestBody的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于特殊原因,客户端需要请求一个put请求,但是什么参数都不需要,具体的参数已经在url里面了,但是Okhttp必须要在Put是传递一个RequestBody参数
源码:

public Builder put(RequestBody body) {
      return method("PUT", body);
    }

...


public Builder method(String method, RequestBody body) {
      if (method == null) throw new NullPointerException("method == null");
      if (method.length() == 0) throw new IllegalArgumentException("method.length() == 0");
      if (body != null && !HttpMethod.permitsRequestBody(method)) {
        throw new IllegalArgumentException("method " + method + " must not have a request body.");
      }
      if (body == null && HttpMethod.requiresRequestBody(method)) {
        throw new IllegalArgumentException("method " + method + " must have a request body.");
      }
      this.method = method;
      this.body = body;
      return this;
    }

可以看到不传就回抛异常,对于这种情况可以如下处理:

RequestBody requestBody = RequestBody.create(null, new byte[]{});
Request request = new Request.Builder()
        .url(url)
        .header("Content-Type",contentType)
        .put(requestBody)
        .build();
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值