How do I post data using okhttp library with content type x-www-form-urlencoded?

You select MediaType MultipartBuilder.FORM which is for uploading the file/image as multipart

public static final MediaType FORM = MediaType.parse("multipart/form-data");

try to send like this as

private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception { 
    RequestBody formBody = new FormBody.Builder().add("search", "Jurassic Park").build(); 
    Request request = new Request.Builder().url("https://en.wikipedia.org/w/index.php").post(formBody).build(); 
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful())
        throw new IOException("Unexpected code " + response); 
    System.out.println(response.body().string()); 
}


For those that may still come here, using with Retrofi2 and passing your data correctly to the request body. Even if you set "application/x-www-form-urlencoded" and you did not pass your data properly, you will still have issue. That was my situstion

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request original = chain.request();
        Request.Builder requestBuilder = original.newBuilder()
                .addHeader("ContentType", "application/x-www-form-urlencoded");
        Request request = requestBuilder.build();
        return chain.proceed(request);
    }
});
OkHttpClient client = httpClient.build();
Retrofit.Builder builder = new Retrofit.Builder()
        .baseUrl(URL)
        .client(client)
        .addConverterFactory(GsonConverterFactory.create());

Retrofit retrofit = builder.build();
Api api = retrofit.create(Api.class);

Then make sure you pass your data to your api endpoint as shown below. NOT as JSON, or class object or string but as request body.

RequestBody formBody = new FormBody.Builder()
        .addEncoded("grant_type", "password")
        .addEncoded("username", username)
        .addEncoded("password", password)
        .build();

call your api service

Call<Response> call = api.login(formBody);

I hope this helps somebody