How to use OKHTTP to make a post request?
As per the docs, OkHttp version 3 replaced FormEncodingBuilder
with FormBody
and FormBody.Builder()
, so the old examples won't work anymore.
Form and Multipart bodies are now modeled. We've replaced the opaque
FormEncodingBuilder
with the more powerfulFormBody
andFormBody.Builder
combo.Similarly we've upgraded
MultipartBuilder
intoMultipartBody
,MultipartBody.Part
, andMultipartBody.Builder
.
So if you're using OkHttp 3.x try the following example:
OkHttpClient client = new OkHttpClient();RequestBody formBody = new FormBody.Builder() .add("message", "Your message") .build();Request request = new Request.Builder() .url("http://www.foo.bar/index.php") .post(formBody) .build();try { Response response = client.newCall(request).execute(); // Do something with the response.} catch (IOException e) { e.printStackTrace();}
The current accepted answer is out of date. Now if you want to create a post request and add parameters to it you should user MultipartBody.Builder as Mime Craft now is deprecated.
RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("somParam", "someValue") .build();Request request = new Request.Builder() .url(BASE_URL + route) .post(requestBody) .build();
private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { RequestBody formBody = new FormEncodingBuilder() .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()); }