Android Volley onResponse function not running - android

Here is my function which I filled in from https://developer.android.com/training/volley/request#java
String url = "http://192.168.1.31:8000/api/social/convert-token";
JSONObject jsonBody = new JSONObject();
try{
jsonBody.put("grant_type", "convert_token");
jsonBody.put("client_id", clientID);
jsonBody.put("client_secret",clientSecret);
jsonBody.put("backend", "facebook");
jsonBody.put("token", facebookAccessToken);
jsonBody.put("user_type", userType);
}catch (JSONException e){
e.printStackTrace();;
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST, url, jsonBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Execute Code
Log.d("LOGIN TO SERVER", response.toString());
// Save server token to local DB
SharedPreferences.Editor editor = sharedPreferences.edit();
try {
editor.putString("token", response.getString("access_token"));
}catch (JSONException e){
e.printStackTrace();
}
editor.commit();
//Start home activity
startActivity(new Intent(Login.this,Home.class));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
The string URL is my Django server, this works properly, I can access it from the web browser on the android phone.
The next block of just converts data I previously got into JSON format. I tested this by copying and pasting the URL, and each parameter in Postman, and it works and returns JSON back.
jsonBody is then passed into the Json Request, along with the URL. The Log.d "LOGIN TO SERVER", is not visible in my log. So I know that the onResponse does not run. Further I put a Log line in the onErrorResponse, and it was visible in my log.
So onReponse does not run, while onError response does. I don't know what the error is.

Three cases,
Check if there are any headers to pass using getHeaders().
2.As it is http and not https, provide android:usesCleartextTraffic="true" in manifest inside . It allows you to access http urls also.
3.You said you have kept logger in Response.onErrorListener(){} and what is the error. If not give it by Log.d("Error", "Error getting "+error.toString);

Related

Unexpected response code 307 for GET request for local service

I'm trying to connect to a localhost web service that I wrote in .net core 2.0. Using the emulator's browser I was able to invoke it and get JSON data back. However, inside my app when I try to get it I'm getting response code 307 back.
public void onClick(View view)
{
String url = String.format("http://10.0.2.2:5000/api/testservice/tickerpnl?ticker=%s&purchaseDate=%s&shares=%s/"
, tickerText.getText().toString(), dateText.getText().toString(), sharesText.getText().toString());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try
{
double pnl = response.getDouble("PNL");
} catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(jsonObjectRequest);
}
On the stacktrace I'm getting the following:
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
E/Volley: [403] BasicNetwork.performRequest: Unexpected response code 307 for http://10.0.2.2:5000/api/testservice/tickerpnl?ticker=AAPL&purchaseDate=1-1-15&shares=1
Again using the link from the stack trace I was able to get the JSON data back just pasting it into the emulator's browser but somehow it just won't work using JsonObjectRequest.
the requestqueue was initialize as
private RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(this);
I found out the issue was that for .net core I had code that redirect http to https so that's why I was getting the 307 error since I was trying to call it using http

Android Json parsing string cannot be converted to json object error

I want to send parameters such as username and password.
I got an error like String cannot be converted to jsonobject.
I dont know what this happening.Anyone pls help me my code is:
JSONObject obj=new JSONObject();
try{
obj.put("username","test");
obj.put("password","test");
} catch (JSONException e) {
}
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
urlJsonObj, obj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq,json_obj_req);
}
There is nothing wrong with the way you are creating JSONObject and putting values in it. Make sure the response received is Json, because your onResponse method accepts JSONObject. You could be receiving String value as response, which could not be converted to JSONObject.
It looks like your response is actually a string and not a json object i.e. {"object":"value"} but rather "object:value". You need to sniff your response via either Stetho, Fiddler or reenact your request via Postman (or Fiddler)
======================
This doesn't answer your question, but this will help you tremendously and make your life easier.
Highly recommend using Gson and Retrofit to make HTTP requests and parse Gson objects easily.
https://github.com/google/gson
http://square.github.io/retrofit/

No authentication challenges found - Volley

Hi I am using volley to parse my api, when i pass the valid credentials it works fine gives me ab auth token and if the credentials are wrong i still want it to parse the response but its giving me "No authentication challenges found" and JSONObject response as null response in return. Is it something with volley or it is something with the php script??
private void sendRequest_getAuth(){
try {
JSONObject jsonBody = new JSONObject();
jsonBody.put("phone", "phn in numeric");
jsonBody.put("password", "pswd");
JsonObjectRequest JSONRequest = new JsonObjectRequest(Request.Method.POST, "the api url", jsonBody,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
jresponse=response;
show_getAuth(jresponse);
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("onError_response",jresponse.toString());
Toast.makeText(LoginActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
show_getAuth(jresponse);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(JSONRequest);
}
required Response which should be parsed:-
{
"errors": [
{
"message": "Invalid Credentials"
}
]
}
Try the following thing:-
Check you Url in Postman (or any applicaiton) and pass invalid credentials and check what response you are receiving from webservice. If you are not getting respose as you have mentioned in you question then its Server side issue (PHP).
Now if you are getting response as above, the kindly check if successfull login and error in login response pattern is same.
Because if the json signature mismatches it won't be able to parse.
If its entering in Error callback kindly mention what is the error server is returning.
Have look at this link too...
java.io.IOException : No authentication challenges found
In case of any doubts, feel free to reply...

how to solve 401 error

I am trying to sent JSON format data (using Volley) from two EditText-views and a method that return unique Device ID to a URL from my Android application and I receive
"[8970] BasicNetwork.performRequest: Unexpected response code 401 for https://gorountsiallyetlasornall:5wxGq5UNlY6wdWmNAyYPVVrN#bulberadev.cloudant.com/notebook"
Here is My method:
private void doPost() {
final String url = "https://gorountsiallyetlasornall:5wxGq5UNlY6wdWmNAyYPVVrN#bulberadev.cloudant.com/notebook";
final String deviceId = getDeviceId(getApplicationContext());
try {
try {
JSONObject jsonObject = new JSONObject();
String title = editTitle.getText().toString();
String content = editContent.getText().toString();
jsonObject.put("title", title);
jsonObject.put("content", content);
jsonObject.put("deviceId", "<" + deviceId + ">");
} catch (JSONException e) {
e.printStackTrace();
}
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
url, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Log.e("VOLLEY", "ERROR");
}
});
requestQueue.add(jsonObjectRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
it should be in a format :
{
"title":"Birth day",
"content":"Buy a gift for my mom!",
"deviceId":"<Device ID>"
}
A 401 is an Unauthorized error.
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error
This means that the user and password is not getting recognized. You're providing it by means of the URL, but this only works for the browser. If the service you're using accepts Basic HTTP authorization headers, this code will provide you the needed headers:
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
String creds = String.format("%s:%s","USERNAME","PASSWORD");
String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT);
params.put("Authorization", auth);
return params;
}
Original code from https://stackoverflow.com/a/18980454/3286819
Of course, username and password needs to be your own. In this case:
username: gorountsiallyetlasornall
password: 5wxGq5UNlY6wdWmNAyYPVVrN
URL: https://bulberadev.cloudant.com/notebook (notice I've removed the user and password)
Some more info: https://yakivmospan.wordpress.com/2014/04/04/volley-authorization/
Error 401 is an HTTP error for unauthorised. This is not a Volley or android related fault. In this case the URL you have provided
https://gorountsiallyetlasornall:5wxGq5UNlY6wdWmNAyYPVVrN#bulberadev.cloudant.com/notebook
Cannot be interpreted by Volley as a login either. This url is sometimes used by cURL and other tools to hardcode the username in password into the URI for Basic Authentication HTTP.
For this your username is gorountsiallyetlasornall and your password is 5wxGq5UNlY6wdWmNAyYPVVrN.
According to Basic Autentication, explained https://luckymarmot.com/paw/doc/HTTP_Basic_Auth
It needs to be converted to Base 64 then added to the header of the request.
I have converted your username and password into a Basic Auth base 64 encoded String for you bellow.
Z29yb3VudHNpYWxseWV0bGFzb3JuYWxsOjV3eEdxNVVObFk2d2RXbU5BeVlQVlZyTg==
Add this into your Volley header by extending a Volley request and overriding the function getHeaders to return a HashMap with the following key value pair.
"Authorization" , "Basic Z29yb3VudHNpYWxseWV0bGFzb3JuYWxsOjV3eEdxNVVObFk2d2RXbU5BeVlQVlZyTg"
Your request will now work.
Please let me know if you want a more detailed explanation.
PS. Hopefully the values you posted in your question is not your real username and password. If so, then don't do that in the future.

Sending login params to Rails server using Volley

Link to Rails server. https://afternoon-sea-5654.herokuapp.com.
I want to send a simple JSON POST to attempt to login. I get the following volley errors
Error
04-09 14:03:56.156 3002-3031/com.digitalnatives.volleytest E/Volley﹕ [244] BasicNetwork.performRequest: Unexpected response code 500 for https://afternoon-sea-5654.herokuapp.com/sessions/create
04-09 14:03:56.160 3002-3002/com.digitalnatives.volleytest E/Volley﹕ [1] 4.onErrorResponse: Error:
I can't tell if it's down to the way I am formatting the request. Here is an example login request using curl manually.
Login -
curl -X POST -d "user[email]=ywaghmare5203#gmail.com&user[password]=12345678&" https://afternoon-sea-5654.herokuapp.com/sessions/create.json
Request perameter: email, password,
Response Perameter:
{"id":10,"username":"yogeshwaghmare1","email":"ywaghmare5203#gmail.com","password_hash":"$2a$10$pvLhzJlVz8Hl86O7N/ekiO2wrwNxbfTZlYPtccY4f7vXYNFs1vq6a","password_salt":"$2a$10$pvLhzJlVz8Hl86O7N/ekiO","last_login_time":null,"is_active":null,"contact_number":"123456","created_at":"2015-04-01T19:20:37.552Z","updated_at":"2015-04-01T19:20:37.552Z"}
JSONObjectRequest code
public void loginTest() {
private final String LOGIN = "https://afternoon-sea-5654.herokuapp.com/sessions/create";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
// old test code : params.put("user[email]=test1#gmail.com&", "user[password]=12345678&");
params.put("user[email]", "test1#gmail.com");
params.put("user[password]", "12345678");
JsonObjectRequest req = new JsonObjectRequest(LOGIN, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
responseText.setText("Worked!");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
responseText.setText("Nope");
}
});
// add the request object to the queue to be executed
AppController.getInstance().addToRequestQueue(req);
}
Actually in response you are not Getting the JSON data. It is returning a HTML message regarding redirection. Your response is 302
Response code 500 means its a server sided syntax error. You can test your api through online API testing platform like Runscope. It really save our time and confusion when we collaborate with web team and android team.
Runscope Link

Categories

Resources