I've been googling for a while now and cannot find the solution to my question that is clean, or not a shady/hacky way of doing things.
I also looked at okhttp's wiki where it clearly shows how to make a POST request with paramaters, albeit it is constructed using the class FormEncodingBuilder
which does not allow the use of HashMap
's in it's creation as it is created as a chain of paramaters, like so (taken from okhhtp's wiki):
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());
}
Here we can see how the paramaters are added to the RequestBody
. But it does not answer how I add a HashMap
full of paramaters directly, not one by one.
The solutions I have so far are simply looping through each EntrySet
in the HashMap
and adding it to the RequestBody
like so (taken from here):
public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
...
parameters = "param1=text¶m2=" + param2 // for example !
request = new Request.Builder()
.url(url + path)
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, parameters))
.build();
Though this does solve my problem, I was wondering if there is a way to directly make a RequestBody
via a HashMap
in okhttp or do I have to use another framework?
This is the code I used in the meanwhile:
String param = "";
for (Map.Entry < String, Object > entry: params.entrySet()) {
param += entry.getKey() + "=" + entry.getValue() + "&";
}
param.substring(0, param.length() - 1);
Request request = new Request.Builder()
.url(endPoint)
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, param))
.build();