问题描述
我需要发出一个带有一些参数的HTTP请求.我需要按原样传递字符串"set(1,2,3)" ,否则至少逗号(,)应该保持不变.不幸的是,无论使用FormBody.Builder的 add
还是 addEncoded
方法,OkHttp 4.9.1都会对我的字符串进行编码.我该如何避免呢?
I need to make an HTTP request with some parameters in the body. I need to pass the string "set(1,2,3)" as is, or at least the commas (,) should be unchanged. Unfortunately, OkHttp 4.9.1 encodes my strings regardless of using FormBody.Builder's add
or addEncoded
methods.How can I avoid it?
示例代码:
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()
));
}
}
结果是:
请求正文(内容类型:"application/x-www-form-urlencoded")为"key = set%28_1_%2C_2_%2C_3_%29& key_encoded = set%28_1_%2C_2_%2C_3_%29"
推荐答案
通过完全跳过使用 FormBody 解决了该问题.要构建HTTP正文,请使用 RequestBody.Companion. create 静态方法:
The problem was solved by skipping use the FormBody at all.To build the HTTP body, the RequestBody.Companion.create static method is used:
RequestBody.Companion.create(bodyString, MediaType.get("application/x-www-form-urlencoded"));
bodyString 是预先编码的主体字符串( key1 = value1& key2 = value2 ...
).
The bodyString is a pre-encoded body string (key1=value1&key2=value2...
).
这篇关于OkHttp如何跳过FormBody表单元素的编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!