FormBody继承抽象类RequestBody
它的CONTENT_TYPE是一个静态常量
private static final MediaType CONTENT_TYPE = MediaType.get("application/x-www-form-urlencoded");
里面还有一个内部类Builder
public static final class Builder {
private final List<String> names = new ArrayList<>();
private final List<String> values = new ArrayList<>();
private final Charset charset;
public Builder() {
this(null);
}
public Builder(Charset charset) {
this.charset = charset;
}
public Builder add(String name, String value) {
if (name == null) throw new NullPointerException("name == null");
if (value == null) throw new NullPointerException("value == null");
names.add(HttpUrl.canonicalize(name, FORM_ENCODE_SET, false, false, true, true, charset));
values.add(HttpUrl.canonicalize(value, FORM_ENCODE_SET, false, false, true, true, charset));
return this;
}
public Builder addEncoded(String name, String value) {
if (name == null) throw new NullPointerException("name == null");
if (value == null) throw new NullPointerException("value == null");
names.add(HttpUrl.canonicalize(name, FORM_ENCODE_SET, true, false, true, true, charset));
values.add(HttpUrl.canonicalize(value, FORM_ENCODE_SET, true, false, true, true, charset));
return this;
}
public FormBody build() {
return new FormBody(names, values);
}
}
所以可以这样使用:
public void doPost(String url, Map<String, String> params, Callback callback) {
FormBody.Builder builder = new FormBody.Builder();
//遍历集合,,,map集合遍历方式
for (String key : params.keySet()) {
builder.add(key, params.get(key));
}
//创建Request....formBody...new formBody.Builder()...add()....build()
Request request = new Request.Builder().url(url).post(builder.build()).build();
Call call = okHttpClient.newCall(request);
call.enqueue(callback);
}