Last year, during Square's 7 days of open source, we announced Mime Craft, which makes it easy to build browser-style HTTP request bodies.
With this week's OkHttp 2 release candidate, we've promoted that MimeCraft code into OkHttp itself. You can encode a form request:
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();
Or a multipart request:
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(
Headers.of("Content-Disposition", "form-data; name=title"),
RequestBody.create(null, "Logo"))
.addPart(
Headers.of("Content-Disposition", "form-data; name=image"),
RequestBody.create(MEDIA_TYPE_PNG, new File("logo.png")))
.build();
Request request = new Request.Builder()
.header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
.url("https://api.imgur.com/3/image")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
It's quite satisfying to build a multipart RequestBody
from other RequestBody
values. Yo dawg.
Complete examples are on the OkHttp recipes page.