Using REDCap API in android keeps getting 403 - android

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

Related

Making GET Request after a POST Request in the same Session with OkHttp in Android Studio

I am trying to retrieve some JSON data using OkHttp in Android Studio from the URL: www.duolingo.com/vocabulary/overview
Before I can get the data using this URL, it requires me to Login into the Duolingo server first (which makes sense since I want it to return data from my profile) so I make a POST request with my credentials using OkHttp. This is my code to achieve that:
OkHttpClient client = new OkHttpClient();
String postUrl = "https://www.duolingo.com/2017-06-30/login?fields=";
String getUrl = "https://www.duolingo.com/vocabulary/overview";
String credentials = "{\"identifier\": \"something#email.com\", \"password\": \"Password\"}";
RequestBody body = RequestBody.create(credentials, MediaType.parse("application/json; charset=utf-8"));
Request request = new Request.Builder()
.url(postUrl)
.post(body)
.build();
client.newCall(request).enqueue(new Callback()
{
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e)
{
Log.i("TAG", "ERROR - " + e.getMessage());
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException
{
if (response.isSuccessful())
{
Log.i("LOG", "LOGGED IN");
}
else
{
Log.i("LOG", "FAILED - " + response.toString());
}
}
});
The Response is successful and I get a 200 Response Code.
Now since I have Logged In, I want to make a GET Request to the URL mentioned above to get the JSON Data. Problem is I do not know how to make a GET Request in succession to the POST Request I just made. OkHttp treats the 2 consecutive requests as separate while I want them to be treated as the same session.
Someone told me Cookies can help but I am totally oblivious to that and how they work. All help is appreciated!

Sending String to server using OkHttpClient POST Method in Service Android

I am sending Json String to my webapi php file from Android Using OkHttpClient from background Service.
The Code of Web Service Is
if (isset($_POST)) {
$data = json_decode(file_get_contents('php://input'), true);
}
The Android Code is :
String requestString = jsonObject.toString();
URL url = new URL("http://cbs.octa.in/webapis/InsertData.php");
OkHttpClient client = new OkHttpClient();
MediaType mdt = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, requestString);
Request request = new Request.Builder()
.url(url)
.header("Content-Type","application/json")
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.v("BGAPI", "RESPONSE ERROR " + e.getMessage());
}
#Override
public void onResponse(Call call, Response response) throws IOException {
Log.v("BGAPI", "RESPONSE " + response);
}
});
The output for this call i am getting is :
RESPONSE ERROR Unable to resolve host "cbs.octa.in": No address associated with hostname
I tried this call from postman and its working , even i confirmed by entering the same url in broweser.
My question is to send data to server in that web api. Please guide me.
Note : For Privacy i have not given the actual domain name.

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.

Moodle Login with an external Android App (Okhttp)

Thanks for your time. Im programming an Android App for School and need a Authentification Form for the Moodle Login (Server ends with /index.php).
My Goal: Get the "Set-Cookie" Header in the Response with the active Cookie in it. This is given, if the Server Status returnes "303(See Other)".
My Question: What should I post to the Login Server, to get the Status "303" (and therefore also the right Cookie) ?
I dont know, if the ".add" Method is the right or wrong or if I should send more or less to the Server.
class MoodleLogin{
public static void FirstRequest(String url) throws Exception {
final OkHttpClient client = new OkHttpClient();
//FORM BODY
RequestBody formBody = new FormBody.Builder()
.add("username", USERNAME) // Username
.addEncoded("password", PASSWORT) //Passwort
.add("token", "6f65e84f626ec97d9eeee7ec45c88303") //Security Key for Moodle mobile web service (I dont know if I need that)
.build();
// A normal Request
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
// Asynchronous Call via Callback with onFailure and onResponse
client.newCall(request).enqueue(new okhttp3.Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.i("Internet", "request failed: " + e.toString());
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) { // Server Status is not 200 - THAT IS WHAT I WANT
Log.d("Server Status", response.message().toString());
throw new IOException("Unexpected code ");
} else { // Server Status is 200(OK)
Log.d("Server Status", response.message().toString());
}
response.body().close();
}
}); // End of "onResponse"
}
This peace of Code only returns the Server Status "200" (what is wrong in my case).
Do anyone know, what I must change to get the Status "303" ? I tested it with hurl.it (A Website for HTTP Requests) and it works only if I post the "username" and "password" like normal Parameters.
Im grateful for every answer and tip !
I answered it myself. So here is the right code:
Connection.Response res = Jsoup
.connect("your Moodle-Login Page")
.data("username", username, "password", password)
.method(Connection.Method.POST)
.execute();
String Login_cookies = res.cookies().toString();
String cookie = Login_cookies.substring(1, 50);
System.out.println("COOKIES: "+cookie);

Appending a param value to a url while making network request in android using okhttp

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/

Categories

Resources