OkHttp如何跳过FormBody表单元素编码

问题描述

我需要在正文中使用一些参数发出 HTTP 请求。我需要按原样传递字符串 "set(1,2,3)",或者至少逗号 (,) 应该保持不变。不幸的是,无论使用 FormBody.Builder 的 addaddEncoded 方法,OkHttp 4.9.1 都会对我的字符串进行编码。 我怎样才能避免它?

示例代码

package my;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.Request;
import okio.Buffer;

public class Check {

  public static void main(final String[] args) throws IOException {
    final String value = "set(_1_,_2_,_3_)";
    Request request = new Request.Builder()
      .url("http://localhost")
      .header("Authorization","Bearer redacted")
      .post(new FormBody.Builder()
        .add("key",value)
        .addEncoded("key_encoded",value)
        .build())
      .build();
    final Buffer buffer = new Buffer();
    request.body().writeto(buffer);
    System.out.println(String.format(
      "Request body (Content-Type: \"%s\") is \"%s\"",request.body().contentType(),buffer.readUtf8()
    ));
  }

}

结果是:

Request body (Content-Type: "application/x-www-form-urlencoded") is "key=set%28_1_%2C_2_%2C_3_%29&key_encoded=set%28_1_%2C_2_%2C_3_%29"

解决方法

问题是通过跳过使用 FormBody 解决的。 要构建 HTTP 正文,请使用 RequestBody.Companion.create 静态方法:

RequestBody.Companion.create(bodyString,MediaType.get("application/x-www-form-urlencoded"));

bodyString 是预编码的正文字符串 (key1=value1&key2=value2...)。