I'm trying to retrieve a token from a JSON response. I've successfully managed to get a response, but I don't know how to retrieve the token.
Here's my code
private void TmdbAuth() {
final String TokenUrl = "https://api.themoviedb.org/3/authentication/token/new?api_key=<<api key goes here>>";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET,
TokenUrl,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.i("jjj", response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
);
requestQueue.add(jsonObjectRequest);
}
and the response of this json
{"success":true,"expires_at":"2019-04-01 10:49:44 UTC","request_token":"request token goes here"}
How do I retrieve only the request_token
Try this #tony
JsonObject object = new JsonObject(response); //obtained response from the server.
String request_token = object.getString("request_token");
Log.e("request_token",request_token); //Just for checking in the logcat.
You can access token String this way
String token = response.optString("request_token");
You can try like this
try{
Log.i("jjj", response.toString());
String requestToken = response.getString("request_token");
}
catch (Exception e) {
e.printStackTrace();
}
Related
I am developing a chatroom and have a this request to get jsonArray from my db, and i want to do a POST jsonObject request to insert msg in db:
public void getMsg(){
String url = "http://192.168.1.57/android/leggi.php";
final TextView chatView =(TextView) findViewById(R.id.chat);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
(Request.Method.POST, url, null, new Response.Listener<JSONArray>() {
String msg = "";
String mittente = "";
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i<response.length(); i++) {
try {
mittente = response.getJSONObject(i).get("mittente").toString();
} catch (JSONException e) {
e.printStackTrace();
}
try {
msg += (response.getJSONObject(i).get("mittente").toString() + ":\n" + response.getJSONObject(i).get("testo").toString() + "\n");
} catch (JSONException e) {
e.printStackTrace();
}
}
chatView.setText(msg);
//chatView.setGravity(Gravity.RIGHT);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
MySingleton.getInstance(this).addToRequestQueue(jsonArrayRequest);
}
can i use the same volley request??? or the request must have different params??? need help :P
This depens on what your servers response is when POSTing the JSONObject.
If the server responses with an JSONArray, you can build your response the same way:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
(Request.Method.POST, url, INSERT_HERE, new Response.Listener<JSONArray>()
...
{
And insert the JSON Object you want to post at the INSERT_HERE position.
If your response differs you need to change the type of Response.Listener<JSONArray>
I am using Volley library to execute my rest APIs.
Using this I have sent email, password entries to URL and receiving response in JSON as:
{
"success": true,
"data": {
"message": false,
"token": "some token value"
}
}
Now I want to parse the 'token' field received from response and do further action. How can this be parsed?
This is the function where I want to parse the response.
public void parseData(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("success").equals("true")) {
Toast.makeText(MainActivity.this,"UserExists",Toast.LENGTH_LONG).show();
////RETRIEVE "token" HERE
else {
Toast.makeText(MainActivity.this,"User not registered",Toast.LENGTH_LONG).show();
}
I have seen this link How to parse JSON Object Android Studio but my "token" field is within another object, so not sure how to do it.
if you want to parse JSON in same manual way you have to do like this to get token.
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getBoolean("success")== true) {
Toast.makeText(MainActivity.this, "UserExists", Toast.LENGTH_LONG).show();
JSONObject dataObj= jsonObject.getJSONObject("data");
String token= dataObj.getString("token");
////RETRIEVE "token" HERE
} else {
Toast.makeText(MainActivity.this, "User not registered", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Here is the solution
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject dataObj = response.getObject("data");
String token = dataObj.getString("token");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
}
);
Please use POJO for parsing. Otherwise you will take more time to do this kind of work.
If you are using Volley, why not simply use the JsonObjectRequest:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET,
url,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// parse the response
JSONObject data= response.getObject("data");
String token = data.getString("token");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
}
);
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
You can try like following.
public void parseData(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("success").equals("true")){
Toast.makeText(MainActivity.this,"UserExists",Toast.LENGTH_LONG).show();
////RETRIEVE "token" HERE
JSONObject dataObject = jsonObject.getObject("data");
String token = dataObject.getString("token");
}
else {
Toast.makeText(MainActivity.this,"User not registered",Toast.LENGTH_LONG).show();
}
}catch(JSONException e) {
Log.e("YourTAG","exceptions "+e.toString());
}
Hope it helps you.
I have build a laravel Rest API with a Jason Web Token. Now I want to make a App which sends data to the Webservice. Here I try to authentificate myself (with name email and password) at first but I do not get the token as a answer. I also do not get a error, nothing happens.
private void sendAndRequestResponse() {
try {
JSONObject jsonBody = new JSONObject();
jsonBody.put("name", "ida");
jsonBody.put("email", "ida#gmail.com");
jsonBody.put("password", "secret");
final String mRequestBody = jsonBody.toString();
//RequestQueue initialized
mRequestQueue = Volley.newRequestQueue(this);
mJsonRequest = new JsonObjectRequest(
Request.Method.POST, url, jsonBody,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
answer.setText(response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
mRequestQueue.add(mJsonRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
you need to start request queue in order to make the request call.
after
mRequestQueue.add(mJsonRequest);
add following
mRequestQueue.start();
im pretty new to Android Studio and I'm trying to build a Get Request using Volley, the Server response is a JsonObject. I tested the code with breakpoints but I wonder why I don't jump into onResponse or why it won't work.
Here's my Code of the Get Method:
public Account GetJsonObject(String urlExtension, String name, Context context) {
String baseURL = "myurl.com/api";
baseURL += urlExtension + "/" + name;
// url will look like this: myurl.com/api/user/"username"
final Account user = new Account("","");
//Account(name, email)
RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(context);
JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.GET, baseURL,null,
new Response.Listener<JSONObject>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONObject response) {
try {
JSONObject obj = response.getJSONObject("userObject");
String username = obj.getString("Username");
String email = obj.getString("Email");
user.setUsername(username);
user.setEmail(email);
}
catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObject);
return user;
}
As #GVillavani82 commented your onErrorResponse() method body is empty. Try to log the error like this
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ERROR", "Error occurred ", error);
}
}
Make sure that you have the below permission set in AndroidManifest.xml file and the api URL is proper.
<uses-permission android:name="android.permission.INTERNET"/>
And JsonObjectRequest class returns Asynchronous network call class. Modify your code like below.
// remove Account return type and use void
public void GetJsonObject(String urlExtension, String name, Context context) {
....
.... // other stuffs
....
JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.GET, baseURL,null,
new Response.Listener<JSONObject>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONObject response) {
processResponse(response); // call to method
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ERROR", "Error occurred ", error);
}
});
requestQueue.add(jsonObject);
}
Now create another method like below
private void processResponse(JSONObject response) {
try {
final Account user = new Account("","");
JSONObject obj = response.getJSONObject("userObject");
String username = obj.getString("Username");
String email = obj.getString("Email");
user.setUsername(username);
user.setEmail(email);
} catch (JSONException e) {
e.printStackTrace();
}
}
I am familiar with Volley and creating a Singleton class, and adding requests to the queue. However, I wish to increase the modularity of volley and simply call all requests through method call to another class instead. I have setup the present action as basis for the common GET request:
public Object getRequest(String params) {
final JSONObject getRequestReturn = new JSONObject();
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET,
VolleySingleton.prefixURL, ((String) null),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
getRequestReturn = response;
Log.v("GET Request value", response.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("GET Request Error", error.toString());
}
});
mRequestQueue.add(getRequest);
return getRequestReturn;
}
However, I have a the perplexing catch 22 error on the assignment of response at:
getRequestReturn = response;
The error notes that getRequestReturn must be declared final to allow for use within the inner class, but upon assigning final, another error appears noting that you cannot assign a value to a final variable.
How can this method be handled?
Declare JSONObject as global and initialize in same place like this.
JSONObject getRequestReturn ;
getRequestReturn = new JSONObject();
public Object getRequest(String params) {
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET,
VolleySingleton.prefixURL, ((String) null),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
Log.v("GET Request value", response.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("GET Request Error", error.toString());
}
});
mRequestQueue.add(getRequest);
return new JSONObject();
}
U can't get response when u return!Volley request is async!
I use EventBus and I do it like this :
When I need to get data from web , i add a request like this.
Then when i get response from web ,I use EventBus to post a event.
I get the event and update my page.
Or U can try the RxAndroid.