How can I pass parameters to android volley post method? - java

I defines a function in an activity class like this:
private void passParam(String pname){
StringRequest compareRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//handle response code
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {}
}) {
#Override
protected Map<String, String> getParams() {
//set post params
Map<String, String> params = new HashMap<String, String>();
params.put("foo", "foo");
params.put("name", pname);//Grammar error, want to use parameter pname
return params;
}
};
requestQ.add(compareRequest);
}
I want to set post parameter "name" value to the parameter pname of function passParam.How to do this conveniently?Thanks!

Related

What's this concept called?

We have this method to make a request using the Volley library:
public void requestWithSomeHttpHeaders() {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://www.somewebsite.com";
StringRequest getRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.d("ERROR","error => "+error.toString());
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("User-Agent", "Nintendo Gameboy");
params.put("Accept-Language", "fr");
return params;
}
};
queue.add(getRequest);
}
Notice the part:
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("User-Agent", "Nintendo Gameboy");
params.put("Accept-Language", "fr");
return params;
}
};
It confuses me because there's no comma before it, so it's not a function argument. If you look at the method definition:
public StringRequest(
int method,
String url,
Listener<String> listener,
#Nullable ErrorListener errorListener) {
super(method, url, errorListener);
mListener = listener;
}
there's no clear code which explains support for this.
What's this concept called and how do you write code that supports this?
This snippet shows the creation of an instance of an anonymous class that extends StringRequest and overrides the getHeaders() method.

Calling an API with string parametrs in Android with Volley

I'am trying to call an API that adds data to a dynamoDB each time a user creates an account .
The url of the API is in the following format :
https://t3x9lg8utf.execute-api.us-east-2.amazonaws.com/prod? id=""&username=""&numero_passeport=""&decision=""
The problem is that when i call the API using volley i get this error :
06-03 14:32:23.599 13503-14515/com.amazonaws.youruserpools.CognitoYourUserPoolsDemo E/Volley: [14796] BasicNetwork.performRequest: Unexpected response code 400 for https://t3x9lg8utf.execute-api.us-east-2.amazonaws.com/prod
The code i used to call the API :
StringRequest sr = new StringRequest(Request.Method.GET, "https://t3x9lg8utf.execute-api.us-east-2.amazonaws.com/prod",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("HttpClient", "success! response: " + response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("HttpClient", "error: " + error.toString());
}
})
{
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("id","\"\"");
params.put("username","\"zaeae\"");
params.put("numero_passeport","\"\"");
params.put("decision","\"\"");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
return params;
}
};
queue.add(sr);
try this
StringRequest sr = new StringRequest(Request.Method.GET, "https://t3x9lg8utf.execute-api.us-east-2.amazonaws.com/prod?id="+Uri.encode(id)+"&username="+Uri.encode(username)+"&numero_passeport="+Uri.encode(numero_passeport)+"&decision="+Uri.encode(decision),
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("HttpClient", "success! response: " + response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("HttpClient", "error: " + error.toString());
}
})
{
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("id","\"\"");
params.put("username","\"zaeae\"");
params.put("numero_passeport","\"\"");
params.put("decision","\"\"");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
return params;
}
};
queue.add(sr);
also pass values for id, username, numero_passeport and decision
? id=""&
These are URL parameters, which cannot be passed via getParams()
You need to append them to the string after Request.Method.GET

Volley returns null on first call from method

I am trying to retrieve data from server using volley, but when I call this method the first time, I get the response from server, but null is returned by the method. If I call it the second time I get the last response.
public String retrieveDataFromServer(String url, String param, final String token){
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
data = new JSONObject(response).toString();
}catch (Exception e){}
//Toast.makeText(getApplicationContext(), "wow" + data, Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
try{
data = new JSONObject(error.toString()).toString();
}catch (Exception e){}
//Toast.makeText(getApplicationContext(), "" +data, Toast.LENGTH_SHORT).show();
}
}) {
/**
* Passing some request headers
*/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
String bearer = "Bearer ".concat(token);
Map<String, String> headersSys = super.getHeaders();
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
//headers.put("token", token);
headersSys.remove("Authorization");
headers.put("Authorization", bearer);
headers.putAll(headersSys);
return headers;
}
};
// Adding request to request queue
addToRequestQueue(stringRequest);
//Toast.makeText(getApplicationContext(), "wow" + data, Toast.LENGTH_SHORT).show();
return data;
}
How do I get the response on first call of method?
You can use call back to return Volley response:
public void retrieveDataFromServer(final VolleyCallback callback) {
StringRequest strReq = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
callback.onSuccess(response);
}
}
}}
Create interface:
public interface VolleyCallback{
void onSuccess(String response);
}
And get result from activity:
String yourString = "";
#override
public void onResume() {
super.onResume();
retrieveDataFromServer(new VolleyCallback(){
#Override
public void onSuccess(String response){
//Get result from here
yourString = response;
}
});
}

First response from server always null with AsyncTask

I've setup a MySql server with a RESTful api to handle my login/signup system for my android app.
I'm creating an ASyncTask to handle the signup POST request, the server should return a JSON object telling us whether it was successful or not. When I input valid details and register on my Android app, the first response in onPostExecute is null. I press the button again and it is correct. What could I be doing wrong?
private class PostAndReadResponseTask extends AsyncTask<Account, Void, String> {
#Override
protected String doInBackground(Account... accounts) {
final Account thisAccount = accounts[0];
RequestQueue requestQueue = Volley.newRequestQueue(RegisterActivity.this);
final String signupURL = "http://localhost:8080/fitnessTrack/api.php?apicall=signup";
StringRequest stringRequest = new StringRequest(Request.Method.POST, signupURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
responseJSON = response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley Error:", error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("username", thisAccount.getUsername());
params.put("password", thisAccount.getPassword());
params.put("email", thisAccount.getEmail());
params.put("firstname", thisAccount.getFirstName());
return params;
}
};
requestQueue.add(stringRequest);
return responseJSON;
}
#Override
protected void onPostExecute(String result) {
System.out.println(result);
}
}
FYI: I edited the URL to say localhost, even though I'm using my own external IP. Even when the response is null, the database does update with the signup data.
The responseJSON is only updated here
#Override
public void onResponse(String response) {
responseJSON = response; // update UI using responseJSON in here
}
so it won't be ready until that method is called with the response. Try printing in there and it should work

android - volley JsonArrayRequest join StringRequest post

I wan't send post from JsonArrayRequest to server and I found some answer and I trying it..
but I got error like this
this is my code
HashMap<String, String> params = new HashMap<String, String>();
public void JSON_DATA_WEB_CALL() {
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL, new JSONObject(params),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("CUSTOM_HEADER", "Yahoo");
headers.put("ANOTHER_CUSTOM_HEADER", "Google");
return headers;
}
};
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
how to fix that?
Use this custom class.
public class CustomJsonArrayRequest extends JsonRequest<JSONArray> {
/**
* Creates a new request.
* #param method the HTTP method to use
* #param url URL to fetch the JSON from
* #param jsonRequest A {#link JSONObject} to post with the request. Null is allowed and
* indicates no parameters will be posted along with request.
* #param listener Listener to receive the JSON response
* #param errorListener Error listener, or null to ignore errors.
*/
public CustomJsonArrayRequest(int method, String url, JSONObject jsonRequest,
Response.Listener<JSONArray> listener, Response.ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
}
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
return Response.success(new JSONArray(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
Implementation in your case should be something like this:
HashMap<String, String> params = new HashMap<String, String>();
public void JSON_DATA_WEB_CALL() {
CustomJsonArrayRequest request = new CustomJsonArrayRequest (Request.Method.POST, GET_JSON_DATA_HTTP_URL, new JSONObject(params),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("CUSTOM_HEADER", "Yahoo");
headers.put("ANOTHER_CUSTOM_HEADER", "Google");
return headers;
}
};
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}

Categories

Resources