I want to do GET request with parameters using volley JsonArrayRequest. I have call getParam() method with parameters but its not calling.
JsonArrayRequest jreq = new JsonArrayRequest(Request.Method.GET,"http://api.openchargemap.io/v2/poi/",null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("TAG", "" + response.toString());
if(response.toString().length() > 1) {
parseJson(response.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("TAG",""+error.toString());
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String,String> map = new HashMap<String,String>();
map.put("output","json");
map.put("countrycode","US");
map.put("latitude","32.57933044");
map.put("longitude","-110.8514633");
map.put("maxresults","100");
map.put("distance","10");
map.put("distanceunit","KM");
map.put("compact","true");
map.put("verbose","false");
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jreq);
I am not getting proper response because volley not calling getParam().
I have searched a lot on stack overflow but not get right answer and volley documentation is not good. Thats why I am puting my question here. Thanks.
As see here:
getParams():
Returns a Map of parameters to be used for a POST or PUT request. Can
throw
* {#link AuthFailureError} as authentication may be required to provide these values.
...
So, for Request.Method.GET use Uri.Builder instead of overriding getParams method for sending query parameters with url
How to use Uri.Builder :
Uri.Builder urlBuilder = new Uri.Builder();
builder.scheme("http")
.authority("api.openchargemap.io")
.appendPath("v2")
.appendPath("poi")
.appendQueryParameter("output",json)
...// add other paramters in same way
;
Get final url from builder:
URL finalURL = new URL(urlBuilder.build().toString());
Use finalURL url for making GET request.
Related
Peeps, I have some problem in understanding the working of volley library, so answer with proper material which can guide me to unobserved aspects of volley is what I am looking forward to.
How does my POST parameters are bind in network request. When I send params after overriding getParams() and by sending jsonObject directly in network request I don't receive any response but some server errors.
Since I am testing my backend on Postman, what postman actually does(my Observation) is it bind the params in url itself. When I copy paste the url in my android code it responds positively.
So, should I code to append my params to url or there's another way round?
I have alredy tried making changes to getHeaders() but it doesn't respond too!
You should use a JsonObjectRequest with a jsonObject containing all your params.
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "8327483274823");
JSONObject jsonObject = new JSONObject(params);
JsonObjectRequest req = new JsonObjectRequest(URL,jsonObject ,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
//Do stuff here
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Handle Errors here
}
});
I am trying to use volley to add a score to my database. I have tested my URL with a POST request using Postman, I have also manually typed the URL with parameters in the android app to the POST request, and that works. so I assume that my issue is in my android code? Or do I have to use the getParams to manually build the url string?
the error I'm getting from my backend:
Error: ER_BAD_FIELD_ERROR: Unknown column 'undefined' in 'field list'
which makes me think that my parameters aren't getting initialized prior to the StringRequest being called.
public void submitHighScore(){
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Toast.makeText(context, response , Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Toast.makeText(context, "Error: unable to submit Score " + error , Toast.LENGTH_SHORT).show();
}
}
){#Override
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError
{
Map<String, String> params = new HashMap<String, String>();
params.put("playerName", "Android test");
params.put("playerScore", "3000");
return params;
}
};
HighScoreSingleton.getInstance(context).addToRequestQueue(postRequest);
For those who may or may not believe me about my code on my server side.
app.post('/api/highScore', function(req,res){
var con = mysql.createConnection({
host: "xxxx",
user: "xxxx",
password: "xxxx",
database: "xxxx"
});
if(req.query!=null){ //
console.log(typeof req.query.playerName);
con.query(`INSERT INTO xxxx (playerScore, playerName) VALUES
(${req.query.playerScore}, "${req.query.playerName}" )`, // async, runs callback aka function
function(err,rows){
if(err) throw err;
res.setHeader('Content-Type', 'text/plain');
res.send('Updated High Score');
});
con.end();
}
});
Thank you in advance, It's very possible I'm overlooking something very simple, otherwise I will just modify my URL in my StringRequest as this seems a bit silly, given the getParams method.
I Hope this will work for you.
I think you need to add header
Override this method.
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = super.getHeaders();
if(params==null)params = new HashMap<>();
params.put("Content-Type","text/plain");
return params;
}
I'm trying to make a Volley JsonObjectRequest (GET) sending Parameters in the following format:
http://localhost:8080/xy?param1=1¶m2=2
My Problem is, I should get a Response-Code 200 (OK), if param1 is "1" and param2 is "2". But I always get the wrong Response Code.
So I think, the request is sending in the wrong format.
Map<String, String> params = new HashMap();
params.put("param1", "1");
params.put("param2", "2");
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, "http://localhost:8080/xy", new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
// Access the RequestQueue through your singleton class.
QueueSingleton.getInstance(LoginActivity.this).addToRequestQueue(jsObjRequest);
Thanks!
Right now, you're providing your JsonObject(params) as the body of the request, which is incorrect. I don't think Volley will append your provided JSON object to your URL for you on a GET request...so you need to do that yourself.
Get rid of adding the post body, and append the params manually on the URL using Uri.Builder.appendQueryParameter(key, value).
Because you use GET method, try to append the params with the url like
int param1Value = 1, param2Value = 2;
String url = "http://localhost:8080/xy?param1=" + param1Value + "¶m2=" + param2Value;
int p1=1;
int p2= 2;
string url= "http://localhost:8080/xy?param1="+p1+"¶m2="+p2;
put this url insted of url you are using..
i am trying to consume a MVC 4 api from my android application
i am using Volley library and it work fine to get data from server
the problem is when i try to send data to the web service which i understand it should be done by using post Method and JsonObjectRequest
my method in MVC Api is :
public class ItemController : ApiController
{
public IEnumerable<string> Post(List<string> val)
{
return val;
}
}
and for volley :
String tag_string_req = "req_login";
Map<String, String> params = new HashMap<>();
params.put("email", "S#b.Com");
params.put("username", "basheq");
JsonObjectRequest req = new JsonObjectRequest(Method.POST ,
AppConfig.URL_REGISTER, new JSONObject(params),new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.d(TAG, "Login Response: " + jsonObject.toString());
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req, tag_string_req);
but i keep getting null in response and it look like the api doesn't parse the parameter .
what is wrong ?? , and is this the proper way to do it or is there a better way ??
The main problem was that i was setting list as a parameter which for some reason does not work
the solution was by wrapping the input parameter into a class and of course change the json structure to correspond to that
I'm using Volley library to access my server data.Volley has inbuilt caching function.I tried to use that as follows.this out put "CACHED RESPONSE". but i don't know how to access the cached data.
void initHttpCall(){
RequestQueue queue = Volley.newRequestQueue(mcontext);
UOBRequest<RateData> myReq = new UOBRequest<RateData>(Method.GET,
Constants.GET_RATES,
RateData.class,
mlistner,
createMyReqErrorListener()){
#Override
public Map<String, String> getHeaders(){
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", getToken());
headers.put("Accept","application/json" );
return headers;
}
};
myReq.setShouldCache(true);
if(queue.getCache().get(Constants.GET_RATES)!=null){
System.out.println("CACHED RESPONSE");
}else{
queue.add(myReq);
}
}
}
This is my response listner and want to get RateData object here.
new Response.Listener<RateData>() {
#Override
public void onResponse(RateData rateData) {
setupCurrencyPager(rateData);
setLastUpdatedTime();
}
});
You misunderstood how Volley's caching system works. The beauty of it is that as a user of Volley, you are unaware of where the response is coming from.
When you add a new request to the RequestQueue, Volley checks if that request already has a cached response. If it does, and that response has not expired yet, it is returned immediately. Otherwise, it goes outside to the network, retrieves the response, caches it and returns it to you.
You don't need that last if statement, simply add it to the queue and Volley will take care of the rest.
try the following code.it will help you sure.
please create a request which you want to pass to server.
JSONObject request = new JSONObject();
request.put("user","user2");
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, url, request, new Response.Listener() {
#Override
public void onResponse(JSONObject response) {
// TODO Auto-generated method stub
Log.v("response:-"+response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(jsObjRequest);
}