使用okhttp时如何将Map添加到RequestBody而不是单独添加键值对?

How to add a Map to RequestBody instead of adding key value pairs individually when using okhttp?

如果我有这个:

RequestBody formBody = new FormEncodingBuilder()
            .add("email", "Jurassic@Park.com")
            .add("tel", "90301171XX")
            .build();

但是我不想单独添加键值对,而是想添加一个大小可变的映射类型变量,我该如何添加它?

自己遍历地图并添加每个 key/value 怎么样?示例:

private FormEncodingBuilder makeBuilderFromMap(final Map<String, String> map) {
    FormEncodingBuilder formBody = new FormEncodingBuilder();
    for (final Map.Entry<String, String> entrySet : map.entrySet()) {
        formBody.add(entrySet.getKey(), entrySet.getValue());
    }
    return formBody;
}

用法:

RequestBody body = makeBuilderFromMap(map)
  .otherBuilderStuff()
  .otherBuilderStuff()
  .otherBuilderStuff()
  .build();

如果您输入正确,则 nbokmans 提供的代码运行良好。这里是更正后的版本:

private RequestBody makeFormBody(final Map<String, String> map) {
    FormEncodingBuilder formBody = new FormEncodingBuilder();
    for (final Map.Entry<String, String> entrySet : map.entrySet()) {
        formBody.add(entrySet.getKey(), entrySet.getValue());
    }
    return formBody.build();
}