使用Okhttp执行put空的RequestBody

来源:互联网 发布:淘宝绽放茉莉恶心 编辑:程序博客网 时间:2024/06/15 10:21

由于特殊原因,客户端需要请求一个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();
原创粉丝点击