Passing whole JsonObject instead of RequestBody in HTTP Request - android

I am creating Requestbody, adding necessary paramters to it and requesting POST method of OKHTTP.
But, Is there any way to pass the whole JsonObject instead of putting seperate parameters to Object of RequestBody ?
Thanks.

for that you have to build your jsonObject and pass that jsonObject as rawString in POST method.
Note : "Google how to pass rawString in POST methode android"

To send JSON Object request we need to create RequestBody Object and Pass it into Request Object. In the RequestBody object, we have to pass Media type and post data as a string.
public static final MediaType MEDIA_TYPE = MediaType.parse("application/json");
JSONObject postdata = new JSONObject();
try {
postdata.put("UserName", "Vishal");
postdata.put("Email", "vishal#####gmail.com");
} catch(JSONException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
RequestBody body = RequestBody.create(MEDIA_TYPE, postdata.toString());
final Request request = new Request.Builder()
.url("YOUR URL")
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "Your Token")
.addHeader("cache-control", "no-cache")
.build();
Hope this will help you.

Try This
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();
}

Related

how to pass web api(post request) url parameters as requestbody in android using okhttp

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();

OkHTTP how to replace team_number from url POST

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();

Issue in POST method with Woocommerce REST API

I'm developing an android app with Woocommerce REST API.
I 'm able to access the data's through this REST api using GET method,
now i'm facing issue in creating new customer using this REST API.
here POST method is not working.
my END_POINT is "http:example.com/wp-json/wc/v1/customers"
the problem is am getting authentication error.
I'm using OkHttp for network call.
Here is my code:
protected String doInBackground(Void... params) {
try {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
String authHeader = Credentials.basic(Config.CONSUMER_KEY, Config.CONSUMER_SECRET);
Log.e(TAG, "doInBackground: auth -> " + authHeader);
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Content-Type", "application/json; charset=utf-8")
.addHeader("Accept", "application/json")
.addHeader("Authorization", authHeader)
.build();
OkHttpOAuthConsumer consumer = new OkHttpOAuthConsumer(Config.CONSUMER_KEY, Config.CONSUMER_SECRET);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new SigningInterceptor(consumer))
.build();
Response response = client.newCall(request).execute();
return response.message();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "doInBackground: " + e.getLocalizedMessage());
return Tag.IO_EXCEPTION;
}
}
Response message is :
{"code":"woocommerce_rest_cannot_create","message":"Sorry, you are not allowed to create resources.","data":{"status":401}}
i don't know where is an issue is.
If anyone experienced this problem, means please share your solution.
Thanks in advance.

OKHttp: Help understanding the "stray" method of "run" or "post"?

I have been looking at the examples in OkHttp for android and I notice there are 2 methods defined, one is called "run" and the other "post" but they never seem to be called. Is something responsible for calling these? How are they called.
Or are these just standard methods, shown as an example that I can change ?
Here is a snippet from the example, obviously i don't understand it fully as they look like "stray" methods, nobody is calling them
here is the "run"
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
and the other snippet here is the "post", i don't see any reference to it
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
Can anyone explain the reasonning behind it ?
thanks.
These are the methods, which will perform the request on the given URL.
You just need to call them like this:
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
String response = run("http://www.url.com");
Also, you can change their name, to anything. It doesn't matter.
The most important part of this code is:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
And you can play with the response object for getting the responseCode, responseBody, Headers etc.

Android OKHttp adding params

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?

Categories

Resources