muyu_nomad muyu_nomad - 3 months ago 16
Android Question

How do I make a poat 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()
.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());
}


but server didn't read parameter.

So, server request parameter's value.

How do I make message?

Answer

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

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