muyu_nomad muyu_nomad - 1 year ago 132
Android Question

How do I make a post request? I use OkHttp? no server response

I need to post a message to server.
- MediaType : application/x-www-form-urlencoded

So, I used FormEncodingBuilder class for making body.
I wrote this code.

Uri.Builder uri = new Uri.Builder()

FormEncodingBUilderformBody = new FormEncodingBUilder()
.add("name", data.getName())
.add("gender", data.getGender())

Request request = new Request.Builder()

try {
Response response = mHttpClient.newCall(request).execute();
String body = response.body().string();

return body;
} catch (Exception e) {
throw new ApiException(0, e.toString());

but server didn't read parameter.

So, server request parameter's value.

How do I make message?

Answer Source

Maybe you need to set charset.
but FormEncodingBuilder class use only MediaType "application/x-www-form-urlencoded".
So, you can make new class like 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) {

public OkHttpFormBuilder add(String name, String value) {
    if(this.content.length() > 0) {

    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);

After you make formbody using this class, try send to server

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download