【发布时间】:2021-06-23 16:09:19
【问题描述】:
我需要在正文中使用一些参数发出 HTTP 请求。我需要按原样传递字符串 "set(1,2,3)" ,或者至少逗号 (,) 应该保持不变。不幸的是,无论使用 FormBody.Builder 的 add 或 addEncoded 方法,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"
【问题讨论】: