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.
Related
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();
}
I have a REDCap project complete setup on Redcap console .
API token generated .
Record saving working from REDCap .
Also from browser tool.
But when I call it from Android App it returns 403 forbidden .
is there anything like set permission for a user.
Also same is working perfectly from ios app .
HashMap<String, String> params = new HashMap<String, String>();
params.put("token","MY TOKEN");
params.put("content","record");
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, String.valueOf(params));
Request request = new Request.Builder()
.url("MY_URL")
.post(body)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(com.squareup.okhttp.Request request, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(com.squareup.okhttp.Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
} else {
// do something wih the result
Log.d("check ok http response ", response.toString());
}
}
});
From Browser tool if I put same URL with selecting POST and set only two params token and content , it return 200 OK .
But from Android it returns 403 . Please help , I have tried several methods in android code .
You're doing this:
RequestBody body = RequestBody.create(JSON, String.valueOf(params));
that's not a valid form body. Do this:
FormBody.Builder formBuilder = new FormBody.Builder()
.add("token","MY TOKEN").add("content","record");
and then
Request request = new Request.Builder()
.url("MY_URL")
.post(formBuilder.build())
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.build();
I am sending a request to server and getting Collection + Json in responce. Every thing is perfect in PostMan.
But when I am doing same things in code using OKHTTP, I am getting some unreadable characters.
Here is my code
OkHttpClient client = new OkHttpClient();
requestBody = new FormBody.Builder()
.add("email", email)
.add("password", psd)
.build();
Request request = new Request.Builder()
.url(url)
.addHeader("Accept", "application/vnd.collection+json")
.addHeader("Accept-Encoding", "gzip")
.addHeader("Authorization", "Basic YWRtaW46cmVhbHNlYw==")
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
String s = response.body().string();
response.body().close();
} catch (Exception e) {
e.printStackTrace();
}
I tried some other url and those are working perfect.
many thanks.
Finally I solved the issue and it wasn't very difficult one although I tried lot's of difficult approaches :P
I solved the issue by removing this line from the code
.addHeader("Accept-Encoding", "gzip")
hope it help to some one other who got stuck like me.
Thanks
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.
What I was doing:
I was using android http library to make http requests
What i am doing:
I have migrated into Oktttp now and i am using below code
In doInBackground of an AsyncTask i am calling the below function
public static String getRequestNoPayload(String urlString) throws Exception {
client.setConnectTimeout(20, TimeUnit.SECONDS); // connect timeout
client.setReadTimeout(20, TimeUnit.SECONDS); // socket timeout
Request request = new Request.Builder()
.url(urlString)
.addHeader("phonenumber",AppController.getPhoneNumber())
.addHeader("authtoken",AppController.getAuthCode())
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
value of url:
String urlString=Keys.login_api+"?phonenumber="+edtPhnoId.getText().toString().trim();
What is happening:
Not able to send requests like this since i am appending the url with
a param ?
How to resolve this ... should i go for any specific encoding
methods, if so which is that one
Any sample would help
Try this
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();
https://publicobject.com/2014/06/12/okhttp-ate-mimecraft/