Can't access volley answer saved - android

I am using this method to access a post Volley request
...
responseVolley = "";
getProductFromDataBase("6130127000035");
Log.d("responseVolley", responseVolley);
...
And my getProductFromDataBase is looking like this
public void getProductFromDataBase(final String bareCode) {
mPreferences = getApplicationContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
this.mEditor = mPreferences.edit();
String url = Constants.URL_SELECT_PRODUCT + "?" + Constants.PARAM_PRODUCT_CODE_BARE + bareCode;
Log.d("URL", url);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
responseVolley = response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("response", "EROOR");
}
}) {
protected HashMap<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
return (HashMap<String, String>) params;
}
};
RequestHandler.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
}
When I am trying to show responseVolley it doesn't even show something in the Logcat ( I've tried many other solutions like shared preferences ) but nothing worked
Am I doing something wrong ?

Using Volley, you should verify these points :
Check and recheck the url string, if you did not deploy your web app, you should use the IP address you used start your server (http://loaclhost:port_number for example).
If your web app is not deployed on the internet yet, your server and your android app must be in the same network (try to make a hotspot from your PC and connect from your device).
In order to see a result in your response, you should return a string for example from the function that route the asked url, i.e. you should have a function in your web app that you want to send data to a function that catch your url in demande, you should return a string in that function.
You should also verify the error log, use a different tag from the response log tag.
Some times you should give some retry time (in case of weak connection):
stringRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 50000;
}
#Override
public int getCurrentRetryCount() {
return 50000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
}
PS: In the code you provided you are sending nothing, you should put strings you want to send like this:
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("key", "value");
return params;
}

You should use callback method to do what you expect. With help of an interface, you can achieve what you actually want. If it doesn't work, let me know.
getProductFromDataBase("6130127000035");
OnResult onResult = new OnResult() {
#override
public void result(String responseVolley) {
Log.d("responseVolley", responseVolley);
}
};
Your getProductFromDataBase() method
interface OnResult {
void result(String responseVolley);
}
public void getProductFromDataBase(final String bareCode) {
mPreferences = getApplicationContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
this.mEditor = mPreferences.edit();
String url = Constants.URL_SELECT_PRODUCT + "?" + Constants.PARAM_PRODUCT_CODE_BARE + bareCode;
Log.d("URL", url);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
onResult.result(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("response", "EROOR");
}
}) {
protected HashMap<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
return (HashMap<String, String>) params;
}
};
RequestHandler.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
}

Related

Trying to send POST from android to node server using volly but the json body is empty on the server

private void postRequest() {
// Request a string response from the provided URL.
// Instantiate the RequestQueue.
String url = "http://10.0.0.9:3000/hello";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
Log.i("*********", "******");
response.put("Hello", "World");
}catch(JSONException e){
Log.i("JSONERROR", e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
Log.i("*********", error.toString());
}
});
jsonObjectRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 1000;
}
#Override
public int getCurrentRetryCount() {
return 1000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
});
This is the Android code
app.post('/hello', function(req,res){
console.log(JSON.stringify(req.body))
})
This is the node js code
So the problem im having is that im printing the body to the console but it keeps showing up empty. As you can see in the postRequest method ive put 'hello as key' and 'world as value' in the jsonobject. So it is calling the correct post request, the body is just empty and cant figure out why that is.
Edit-----
Ive checked the content with wireshark and content length is 0 so im not sending anything it seems. if im understanding this correctly
You are not sending anything inside of your POST body request, that's why you are getting an empty response at your server-side.
For sending POST parameters, you will need to override getParams() method:
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
map.put("param1", "hello");
map.put("param2", "This is a post request");
return map;
}
Here is the complete example:
private void postRequest() {
// Request a string response from the provided URL.
// Instantiate the RequestQueue.
String url = "http://10.0.0.9:3000/hello";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
Log.i("*********", "******");
response.put("Hello", "World");
}catch(JSONException e){
Log.i("JSONERROR", e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
Log.i("*********", error.toString());
}
}) { // HERE TO ADD POST PARAMETERS
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
map.put("param1", "hello");
map.put("param2", "This is a post request");
return map;
}
};
jsonObjectRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 1000;
}
#Override
public int getCurrentRetryCount() {
return 1000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
});

How to send parameters to backend, and get response message, using GET method in volley, android?

I want to send three parameters "guestEmail", "latitude" and "longitude" to backend and get a message of success from backend if it is successful.
I have tried doing this:
public void myGetFunc()
{
final String url = "....";
// prepare the Request
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
// display response
Log.d("Response", response.toString());
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", response);
}
}
)
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String> ();
params.put("guestEmail", "abc#xyz.com");
params.put("latitude", "12");
params.put("longitude", "12");
return params;
}
};
// add it to the RequestQueue
queue.add(getRequest);
}
This method is invoked when the 'SOS' button is clicked.
But right now, nothing happens on clicking the 'SOS' button.
Please help!
If you are going to use GET you query parameters and build the string yourself
private static final String URL = "http://www.test.com?value1={val1}&value2={val2}";
String requestString = URL;
requestString.replace("{val1}", "1");
requestString.replace("{val2}", "Bob");
StringRequest strreq = new StringRequest(Request.Method.GET,
requestString,
new Response.Listener<String>() {
#Override
public void onResponse(String Response) {
// get response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError e) {
e.printStackTrace();
}
});
Volley.getInstance(this).addToRequestQueue(strreq);
If you are going to use POST us a body
public class LoginRequest extends Request<String> {
// ... other methods go here
private Map<String, String> mParams;
public LoginRequest(String param1, String param2, Listener<String> listener, ErrorListener errorListener) {
super(Method.POST, "http://test.url", errorListener);
mListener = listener;
mParams = new HashMap<String, String>();
mParams.put("paramOne", param1);
mParams.put("paramTwo", param2);
}
#Override
public Map<String, String> getParams() {
return mParams;
}
}
If you want to pass parameters than you need to use POST method otherwise for GET , just pass values in URL itself.

Sending POST Data in Android for Kairos API

I am looking to do as per the image says:
Following is the code I am trying to implement from that image:
RequestQueue queue = Volley.newRequestQueue(this);
String url ="https://api.kairos.com/enroll";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Log.i("Response is: " , response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// mTextView.setText("That didn't work!");
}
})
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("app_id", "4985f625");
params.put("app_key", "aa9e5d2ec3b00306b2d9588c3a25d68e");
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
Now I do not get how to add that JSONObject part into my POST Request, and also how to add the Content-Type Header.
I found a similar question here. See the code below. You have to override the getBodyContentType method.
public String getBodyContentType()
{
return "application/json";
}
for content type header you can do the following
StringRequest request = new StringRequest(Request.Method.PUT,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
listener.onResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(#NonNull VolleyError error) {
if (error.networkResponse != null) {
errorListener.onErrorResponse(error.networkResponse.statusCode, null);
} else {
Log.e(TAG, "An error occurred while trying to verify sms: ", error);
errorListener.onErrorResponse(500, null);
}
}
}) {
#NonNull
#Override
protected Map<String, String> getParams() {
return data;
}
#NonNull
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type",
"application/x-www-form-urlencoded");
return headers;
}
};
And for send Json object I suggest create Json object like this
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("11", 3);
jsonObject.put("12", 4);
jsonObject.put("13", 5);
} catch (JSONException e) {
e.printStackTrace();
}
Then you can pass this object as string by jsonObject.toString() and pass it in parameters like pass any string like the following
#NonNull
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("json", jsonObject.toString();
return params;
}

StringRequest with JSON body

I'm trying to send a request using Volley but I can't figure how to make it work.
I need to send a POST request with JSON encoded data as the body, but after hours of trying different things I still can't make it work.
This is my current code for the request:
User user = User.getUser(context);
String account = user.getUserAccount();
String degreeCode = user.getDegreeCode();
final JSONObject body = new JSONObject();
try {
body.put(NEWS_KEY, 0);
body.put(NEWS_DEGREE, degreeCode);
body.put(NEWS_COORDINATION, 0);
body.put(NEWS_DIVISION, 0);
body.put(NEWS_ACCOUNT, account);
} catch (JSONException e) {
e.printStackTrace();
}
StringRequest request = new StringRequest(Request.Method.POST, GET_NEWS, new Response.Listener<JSONObject>() {
#Override
public void onResponse(String response) {
Log.i(TAG, response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + getMessage(error, context));
Toast.makeText(context, getMessage(error, context), Toast.LENGTH_SHORT).show();
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
return body.toString().getBytes();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type","application/json");
return headers;
}
};
queue.add(request);
But this code always returns "Bad request error"
Some things I've tried:
Override getParams() method instead of getBody(). (Didn't work)
Send a JSONObjectRequest with the body on the constructor. This one worked, but because my web service returns a String value I always get a ParseError. That's why I'm using StringRequest.
Any help is very much appreciated.
As already mentioned on njzk2's comment, the easiest way is to override getBodyContentType() instead. Overriding getHeaders() could probably work too, but you need to put all necessary headers, not only Content-Type, since you basically override the headers that the original method set.
Your code should look like this:
StringRequest request = new StringRequest(...) {
#Override
public byte[] getBody() throws AuthFailureError {
return body.toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
};

Android Volley POST string in body

I'm trying to use Volley library to communicate with my RESTful API.
I have to POST string in the body, when I'm asking for the bearer Token. String should look like this:
grant_type=password&username=Alice&password=password123
And header:
Content-Type: application/x-www-form-urlencoded
More info about WebApi Individual Accounts:
http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api
Unfortunately I can't figure out how can I solve it..
I'm trying something like this:
StringRequest req = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.v("Response:%n %s", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", "User0");
params.put("password", "Password0");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
return headers;
}
};
I'm getting 400 Bad Request all the time.
I think that I'm actually sending request like this:
grant_type:password, username:User0, password:Password0
instead of:
grant_type=password&username=Alice&password=password123
I would be very grateful if anyone has any ideas or an advice..
To send a normal POST request (no JSON) with parameters like username and password, you'd usually override getParams() and pass a Map of parameters:
public void HttpPOSTRequestWithParameters() {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://www.somewebsite.com/login.asp";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR","error => "+error.toString());
}
}
) {
// this is the relevant method
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
// volley will escape this for you
params.put("randomFieldFilledWithAwkwardCharacters", "{{%stuffToBe Escaped/");
params.put("username", "Alice");
params.put("password", "password123");
return params;
}
};
queue.add(postRequest);
}
And to send an arbitary string as POST body data in a Volley StringRequest, you override getBody()
public void HttpPOSTRequestWithArbitaryStringBody() {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://www.somewebsite.com/login.asp";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR","error => "+error.toString());
}
}
) {
// this is the relevant method
#Override
public byte[] getBody() throws AuthFailureError {
String httpPostBody="grant_type=password&username=Alice&password=password123";
// usually you'd have a field with some values you'd want to escape, you need to do it yourself if overriding getBody. here's how you do it
try {
httpPostBody=httpPostBody+"&randomFieldFilledWithAwkwardCharacters="+URLEncoder.encode("{{%stuffToBe Escaped/","UTF-8");
} catch (UnsupportedEncodingException exception) {
Log.e("ERROR", "exception", exception);
// return null and don't pass any POST string if you encounter encoding error
return null;
}
return httpPostBody.getBytes();
}
};
queue.add(postRequest);
}
As an aside, Volley documentation is non-existent and quality of StackOverflow answers is pretty bad. Can't believe an answer with an example like this wasn't here already.
First thing, I advise you to see exactly what you're sending by either printing to the log or using a network sniffer like wireshark or fiddler.
How about trying to put the params in the body? If you still want a StringRequest you'll need to extend it and override the getBody() method (similarly to JsonObjectRequest)
I know this is old, but I ran into this same problem and there is a much cleaner solution imo found here: How to send a POST request using volley with string body?

Categories

Resources