由于特殊原因,客户端需要请求一个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();
本文介绍在使用OkHttp发起PUT请求时,如果不需要携带额外参数,如何正确构造请求。通过创建空的RequestBody对象来避免OkHttp强制要求RequestBody的情况。
1907

被折叠的 条评论
为什么被折叠?



