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.
Related
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!
I'm trying to send data from an Android device to a web server using Flask.
I'm just testing by returning some strings.
If I do a post request on POSTMAN to IP_Address/playlists with {"spotify_token":"test token"} I'll get the proper response. {"result":"received token"}
But if I try to send a similar HTTP Post request on Android with OkHTTP I get error 405. 192.168.0.105 - - [19/Jul/2018 17:23:37] "POST //playlists HTTP/1.1" 405 -
Response from server:
Allow: HEAD, GET, OPTIONS
Content-Length: 178
Server: Werkzeug/0.14.1 Python/3.7.0
Date: Fri, 20 Jul 2018 01:57:56 GMT
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>405 Method Not Allowed</title>
<h1>Method Not Allowed</h1>
<p>The method is not allowed for the requested URL.</p>
I checked my code with other answers and as far as I can tell it looks correct.. Also, I'm able to do a GET request in my home page fine.
Android Code
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
public void onClick(View view){
client = new OkHttpClient();
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("UserId", "test token");
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody requestBody = RequestBody.create(JSON, jsonObject.toString());
Request request = new Request.Builder()
.url(IP_ADDRESS + "/playlists")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.e("ExportButton", e.toString());
}
#Override
public void onResponse(Call call, Response response) throws IOException {
Log.e("ExportButton", response.body().string());
if(response.isSuccessful()){
final String myResponse = response.body().string();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
messageWindow.setText(myResponse);
}
});
}
}
});
Flask code
#app.route('/playlists', methods =["POST"])
def get_playlists():
data = request.get_json()
spotify_token = data['spotify_token']
print(spotify_token)
return jsonify({'result': 'received token'})
I printed out the response and found the full URL it was going to was "http://IP_Address//playlists" (there were two "/"s which is why it was getting the error.
Thanks Mushtu.
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'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.
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);