自定义FormBuilder
public class OkHttpFormBuilder { private static final MediaType CONTENT_TYPE = MediaType.parse("application/x-www-form-urlencoded"); private final StringBuilder content = new StringBuilder(); private String encoding="utf-8"; public OkHttpFormBuilder(){} public OkHttpFormBuilder(String encoding){ if(!TextUtils.isEmpty(encoding)){ this.encoding=encoding; } } /** Add new key-value pair. */ public OkHttpFormBuilder add(String name, String value) { if (content.length() > 0) { content.append('&'); } try { content.append(URLEncoder.encode(name, encoding)) .append('=') .append(URLEncoder.encode(value, encoding)); } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } return this; } public RequestBody build() { if (content.length() == 0) { throw new IllegalStateException("Form encoded body must have at least one part."); } // Convert to bytes so RequestBody.create() doesn't add a charset to the content-type. byte[] contentBytes = content.toString().getBytes(Charset.forName(encoding)); return RequestBody.create(CONTENT_TYPE, contentBytes); } }使用
OkHttpFormBuilder builder = new OkHttpFormBuilder("gb2312");