I'm using OkHTTP for making a post request to my server. I know I can build a request like this:
RequestBody formBody = new FormEncodingBuilder()
.add("param1", param1)
.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
So what I want to do is to add the parameters dynamically. E.g:
RequestBody formBody = new FormEncodingBuilder()
for (ParamsArray m : requestParams) {
formBody.add("param1", requestParams.value);
}
But there's no function add for a RequestBody and I don't know if it is possible to convert a FormEncodingBuilder to a RequestBody.
Thank you!
A FormEncodingBuilder will turn into a RequestBody when you build it. Looking at the documentation, something like this ought to work.
FormEncodingBuilder formBodyBuilder = new FormEncodingBuilder()
for (ParamsArray m : requestParams) {
formBodyBuilder.add("param1", requestParams.value);
}
RequestBody body = formBodyBuilder.build()
The documentation is available here:
https://square.github.io/okhttp/2.x/okhttp/com/squareup/okhttp/FormEncodingBuilder.html
As of 3.0.0, the FormEncodingBuilder is gone:
Form and Multipart bodies are now modeled. We've replaced the opaque
FormEncodingBuilder with the more powerful FormBody and
FormBody.Builder combo. Similarly we've upgraded MultipartBuilder into
MultipartBody, MultipartBody.Part, and MultipartBody.Builder.
So replace with FormBody.Builder for these versions.
try this
FormEncodingBuilder formBodyBuilder = new FormEncodingBuilder();
for (ParamsArray m : requestParams) {
formBodyBuilder.add("param1", requestParams.value);
}
RequestBody formBody = formBodyBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Instead of FormEncodingBuilder
use
Builder paramBuilder = new FormBody.Builder();
paramBuilder.add("param1","value1");
paramBuilder.add("param2","value2");
RequestBody requestBody = paramBuilder.build();
Related
I was trying to implement postman's working as following for android app:
Here is my java codes:
MediaType CONTENT_TYPE = MediaType.parse("application/x-www-form-urlencoded");
RequestBody requestBody = new MultipartBody.Builder()
.setType(CONTENT_TYPE)
.addFormDataPart("phoneNumber", phone)
.addFormDataPart("serviceType", type)
.addFormDataPart("stripeToken", token)
.addFormDataPart("serviceCost", String.valueOf(amount))
.build();
final Request request = new Request.Builder()
.url(Const.URL_HEROKU_BASE+"payment/charge")
.post(requestBody)
.build();
It makes crash ...
I had the same issue when using the public api/login of this free rest service.
In postman, when passing body as application/x-www-form-urlencoded works. But in OkHttp3 MultipartBody doesn't work.
As #shindi suggested this code works perfectly for this api.
RequestBody requestBody = new FormBody.Builder()
.add("email", "some_email")
.add("password", "some_password")
.build();
.header() wasn't needed for the request either. Works for me. Hope it helps.
Change:
MultipartBody
to:
FormBody
I think you are not adding the content type properly:
Change this:
final Request request = new Request.Builder()
.url(Const.URL_HEROKU_BASE+"payment/charge")
.post(requestBody)
.build();
to:
final Request request = new Request.Builder()
.header("Content-Type", "application/x-www-form-urlencoded")
.url(Const.URL_HEROKU_BASE+"payment/charge")
.post(requestBody)
.build();
and remove the .setType(CONTENT_TYPE) part.
Let use FormBody as suggested at https://stackoverflow.com/a/53261129/2013887
And don't forget to use correct #RequestBody type, e.g MultiValueMap for application/x-www-form-urlencoded media type
I have a asp.net web api url which accepts query string parameters but its actually a post request. I am trying to access the same url in android but not sure how to pass the query parameters. Any help will be appreciated as I am not an android developer basically.
Here is the snippet:
RequestBody formBody = new FormBody.Builder()
.add("email", mEmail.toLowerCase())
.add("password", mPassword)
.build();
//2. Bind the request Object
Request req = new Request.Builder()
.url(loginAPI).post(formBody)
.build();
Response response = client.newCall(req).execute();
This is the solution:
String loginAPI = "http://api.myapi.com/api/authentication?email="+mEmail.toLowerCase()+"&password="+mPassword;
RequestBody reqbody = RequestBody.create(null, new byte[0]);
Request req = new Request.Builder()
.url(loginAPI)
.method("POST", reqbody)
.build();
Response response = client.newCall(req).execute();
I am using OkHTTP and I have some problems when I try to make a post request.
Here is my code :
client = new OkHttpClient();
formBody = new FormBody.Builder()
.add(Constant.DIRECTION, Constant.OUT)
.add(Constant.LIMIT, Constant.docs_limit)
.add(Constant.IMPORTED, Constant.FALSE)
.addEncoded("statuses[]", "4")
request = new Request.Builder()
.url(url)
.addHeader(Constant.AUTH_TOKEN, sharedPreferences.getString(Constant.TOKEN, ""))
.post(formBody)
.build();
when I try to send
"statuses[]", "4"
in the debugger it shows that brackets converted to "statuses%5B%5D".
How to fix that? Sorry for my poor english.
I have url like this.
http://host/parallel/team/:team_number.json
and it has post params.
like team_number, team_name.
How to make a post request such that i replace team_number to team number with a value.
Does :team_number need to be handled differently ?
So far i have done
RequestBody formBody = new FormBody.Builder()
.addEncoded(TEAM_NUMBER,tracking_number)
.add(TRACK_NAME, name)
.build();
Request request = new Request.Builder()
.url(SEND_TRACKING_DATA)
.post(formBody)
.build();
Response response = CoreApplication.okHttpClient.newCall(request).execute();
return response.body().string();
How is it possible to append params to an OkHttp Request.builder?
//request
Request.Builder requestBuilder = new Request.Builder()
.url(url);
I've managed the add header but not params.
Here is a complete example on how to use okhttp to make post request (okhttp3).
To send data as form body
RequestBody formBody = new FormBody.Builder()
.add("param_a", "value_a")
.addEncoded("param_b", "value_b")
.build();
To send data as multipart body
RequestBody multipartBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("fieldName", fileToUpload.getName(),RequestBody.create(MediaType.parse("application/octet-stream"), fileToUpload))
.build();
To send data as json body
RequestBody jsonBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
jsonObject.toString());
Now create request
Request request = new Request.Builder()
.addHeader("header_a", "value_a") // to add header data
.post(formBody) // for form data
.post(jsonBody) // for json data
.post(multipartBody) // for multipart data
.build();
Response response = client.newCall(request).execute();
** fileToUpload is a object of type java File
** client is a object of type OkHttpClient
Maybe you mean this:
HttpUrl url = new HttpUrl.Builder().scheme("http").host(HOST).port(PORT)
.addPathSegment("xxx").addPathSegment("xxx")
.addQueryParameter("id", "xxx")
.addQueryParameter("language", "xxx").build();
You can use this lib: https://github.com/square/mimecraft:
FormEncoding fe = new FormEncoding.Builder()
.add("name", "Lorem Ipsum")
.add("occupation", "Filler Text")
.build();
Multipart content:
Multipart m = new Multipart.Builder()
.addPart(new Part.Builder()
.contentType("image/png")
.body(new File("/foo/bar/baz.png"))
.build())
.addPart(new Part.Builder()
.contentType("text/plain")
.body("The quick brown fox jumps over the lazy dog.")
.build())
.build();
See here:
How to use OKHTTP to make a post request?