Reputation: 31
To send a POST request with OkHttp I've seen they use FormBody.Builder, but that requires me to manually input each name and value for the POST data. Is there a way to create a RequestBody with a single String with the POST data? For example, instead of
FormBody.Builder bodyBuilder = new FormBody.Builder();
bodyBuilder.add("name", "value");
bodyBuilder.add("name2", "value2");
...just doing
bodyBuilder.add("name=value&name2=value2");
Upvotes: 3
Views: 4843
Reputation: 3179
You can also simply do this with the latest version:
val reqBody = "foo=bar"
val request = Request.Builder().post(reqBody.toRequestBody()).build()
Upvotes: 0
Reputation: 33
You can do it like this:
RequestBody body = RequestBody.create(MediaType.get("application/x-www-form-urlencoded"), "key1=value1&key2=value2");
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Upvotes: 3
Reputation: 559
Create a MediaType variable named FORM:
public static final MediaType FORM = MediaType.parse("multipart/form-data");
Create a RequestBody using the FORM variable and your unparsed params (String):
RequestBody requestBody = RequestBody.create(FORM, params);
Post the full requestBody variable.
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Upvotes: 0
Reputation: 32550
Sure, using RequestBuilder
Request request = new Request.Builder()
.url(url)
.post(body) // here you put your body
.build();
But URL encoding and other related stuff will be on your side.
Upvotes: 0