Calling an API with string parametrs in Android with Volley - java

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

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.

how to get raw string response in android using volley login?

I'm trying to receive raw string response using volley, but I'm not able to get any type of response. Below is my code that I have tried while hiring the user.
I'm able to get key value pair response, but if we are using raw string, it's not throwing any response in log cat.
username = editTextUsername.getText().toString().trim();
password = editTextPassword.getText().toString().trim();
Toast.makeText(this, "Button Hit", Toast.LENGTH_SHORT).show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
if (response.trim().equals("Message:Valid User")) {
Toast.makeText(PostLogin.this, "Resposne"+response.toString(), Toast.LENGTH_SHORT).show();
Log.d("Response:",""+response.toString());
} else {
Toast.makeText(PostLogin.this, response, Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(PostLogin.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put(KEY_USERNAME, username);
map.put(KEY_PASSWORD, password);
map.put("Content-Type","application/json");
return map;
}
#Override
public byte[] getBody() throws com.android.volley.AuthFailureError {
String str = "{\"login\":\""+username+"\",\"password\":\""+password+"\"}";
return str.getBytes();
};
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}

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);
}

Get Auth AcessToken from Paypal Android sdk

I have tried to get auth Access token using below code.and based on this code ,we will get Full transaction detail of Paypal.
Below code is working fine in Lollipop and above, but when we run my app in lolipop below version then not getting any response from Paypal SDK.I did lot of R&D for this issue.Please give me solution of this.
My Working Code in Lollipop and above:
public void getAcessToken(final String PayID) {
base64 = "Basic " + Base64.encodeToString((URLs.PAYPAL_CLIENTID + ":" + URLs.PAYPAL_SECRET_KEY).getBytes(), Base64.NO_WRAP);
Log.i("TAG", "Base64=" + base64);
if (!CM.isInternetAvailable(this)) {
CM.showPopupCommonValidation(this, getResources().getString(R.string.internet_unavailable_msg), false);
return;
}
showDialog();
String url = "https://api.sandbox.paypal.com/v1/oauth2/token";
Log.i("WebCalls", url);
StringRequest stringRequest = new StringRequest(Request.Method.POST,
url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
KcsLog.i("WebCalls", response.toString());
String AccessToken = CM.getValueFromJson("access_token", response);
String token_type = CM.getValueFromJson("token_type", response);
GetTransactionID(token_type + " " + AccessToken, PayID);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dismissDialog();
CM.showVolleyErrorMessage(error, ViewGiftCode.this, "", false);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> post = new HashMap<String, String>();
post.put("grant_type", "client_credentials");
return post;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> post = new HashMap<String, String>();
post.put("Accept", "application/json");
post.put("Accept-Language", "en_US");
post.put("Content-Type", "application/x-www-form-urlencoded");
post.put("Authorization", base64);
return post;
}
};
((MainApplications) getApplicationContext()).volley.addToRequestQueue(stringRequest);
}
Please give me solution for below lollipop.

How can I pass parameters to android volley post method?

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!

Categories

Resources