我需要向服务器发帖子。 - MediaType:application / x-www-form-urlencoded
所以,我使用FormEncodingBuilder类来制作body。 我写了这段代码。
Uri.Builder uri = new Uri.Builder()
.scheme(SCHEME)
.encodedAuthority(HOST)
.appendPath("v3")
.appendPath("svc")
.appendPath("auth");
FormEncodingBUilderformBody = new FormEncodingBUilder()
.add("name", data.getName())
.add("gender", data.getGender())
.build();
Request request = new Request.Builder()
.url(uri.build().toString())
.post(formBody)
.build();
try {
Response response = mHttpClient.newCall(request).execute();
String body = response.body().string();
return body;
} catch (Exception e) {
throw new ApiException(0, e.toString());
}
但是服务器没有读取参数 所以,服务器请求参数的值 我如何发消息?
答案 0 :(得分:0)
也许你需要设置charset 但是FormEncodingBuilder类只使用MediaType“application / x-www-form-urlencoded” 所以,你可以创建像FormEncodingBuilder这样的新类。
public class OkHttpFormBuilder {
private MediaType CONTENT_TYPE = MediaType.parse("application/x-www-form-urlencoded;charset=utf-8");
private final StringBuilder content = new StringBuilder();
public OkHttpFormBuilder() {
}
public MediaType getCONTENT_TYPE() {
return CONTENT_TYPE;
}
public void setCONTENT_TYPE(MediaType CONTENT_TYPE) {
this.CONTENT_TYPE = CONTENT_TYPE;
}
public OkHttpFormBuilder add(String name, String value) {
if(this.content.length() > 0) {
this.content.append('&');
}
try {
this.content.append(URLEncoder.encode(name, "UTF-8")).append('=').append(URLEncoder.encode(value, "UTF-8"));
return this;
} catch (UnsupportedEncodingException var4) {
throw new AssertionError(var4);
}
}
public String getContent()
{
return this.content.toString();
}
public RequestBody build() {
if(this.content.length() == 0) {
throw new IllegalStateException("Form encoded body must have at least one part.");
} else {
byte[] contentBytes = this.content.toString().getBytes(Util.UTF_8);
return RequestBody.create(CONTENT_TYPE, contentBytes);
}
}}
使用此类制作formbody后,尝试发送到服务器