What's this concept called? - java

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.

Related

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

switch case in getparams in volley

I am trying to achieve single function that can be used to do server calls for different URL request.To do this I need to send different parameters for different URL.
I am doing this and it is showing "Invalid Request".
Can anyone suggest me how to achieve this.
#Override
public Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
switch (URL)
{
case "REFERRALS_LIST":
params.put("customer_id", data.GetData(SharedDataHandler.CUSTOMER_ID));
params.put("first_name", argslist.get(0));
params.put("last_name", argslist.get(1));
params.put("address", argslist.get(2));
params.put("mobile", argslist.get(3));
params.put("email", argslist.get(4));
params.put("contact_home", argslist.get(5));
Log.d("test", "getParams: "+argslist.get(0)+argslist.get(1)+argslist.get(2)+argslist.get(3)+argslist.get(4)+argslist.get(5));
break;
}
return params;
}
Hello Try this if it helps
1) performVolleyRequest is method for making volley request
2) I maintained Switch Case for Handling the various requests
3) You Have to use requestType variable according to your requirement as I left it blank I didn't know when your required it
public class MainActivity extends AppCompatActivity {
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_EMAIL = "email";
String requestType="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switch (requestType){
case "Registration":
Map<String, String> dynamicParams = new HashMap<String, String>();
dynamicParams.put(KEY_USERNAME, "userName");
dynamicParams.put(KEY_PASSWORD, "password");
dynamicParams.put(KEY_EMAIL, "email");
final String REGISTER_URL_REG = "http://foo.com/volleyRegister.php";
performVolleyRequest(dynamicParams,REGISTER_URL_REG);
break;
case "Login":
Map<String, String> dynamicParamsLogin = new HashMap<String, String>();
dynamicParamsLogin.put(KEY_USERNAME, "userName");
dynamicParamsLogin.put(KEY_PASSWORD, "password");
final String REGISTER_URL_LOGIN = "http://foo.com/volleyLogin.php";
performVolleyRequest(dynamicParamsLogin,REGISTER_URL_LOGIN);
break;
}
}
private void performVolleyRequest(final Map<String, String> paramDynamic,final String REGISTER_URL) {
StringRequest stringRequest = new StringRequest(DownloadManager.Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params=paramDynamic;
return params;
}
};
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);
}

Why Android Studio prompt “Method doesn't override its superclass”?

I want to use volley to build http connection with authentication. Following this answer I add the segment
#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;
}
in Anonymous Inner Class StringRequest , and it looks like:
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
//the segment below is what I add
#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;
}
//the segment above is what I add
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
However, IDE hints that getHeaders() doesn't override its superclass.
Why?I found that StringRequest extends class Request<String>, and the latter does have a method called getHeaders().
You are overriding public Map<String, String> getHeaders() inside a new instance of Response.Listener<String> instead of Request<String> and Response.Listener<String> does not have such method (only onResponse(String)).

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