Android volley library is not accepting parameters in url from getParam() - android

Android volley library is not accepting parameters from getParam() method.If it is given in query String then it works.I tried both GET and POST it doesn't works. But I want to give parameters POST Method.please check the code I have posted below.
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url = AppConstants.WEBSERVICE_URL
+ AppConstants.WEBSERVICE_URL_POST_COMMENT;
StringRequest getRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// response
Log.d("Response_postComment", response);
Intent intent = new Intent(getApplicationContext(),
ReviewActivity.class);
intent.putExtra("serviceId", servicePosition);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> pars = new HashMap<String, String>();
pars.put("Content-Type", "application/x-www-form-urlencoded");
return pars;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError{
Map<String, String> params = new HashMap<String, String>();
params.put("rating", ratingBar.getRating() + "");
params.put("com_content", comments.getText() + "");
params.put("user_id", AppConstants.APP_LOGIN_USER_ID);
params.put("comm_post_ID", AppConstants.arrListServiceDetail
.get(servicePosition).getId() + "");
return params;
}
};
getRequest.setRetryPolicy(new DefaultRetryPolicy(500000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(getRequest);

getParam() method not working with GET request on volley.its working fine with POST methods.you have to set up complete URL with parameters.

I faced the same issue as you are facing now, but comes up with solution of making a custom request by making the core class Request as the super class of this request. In this i am passing params in constructor, then returning it to the getParams() overridden method as below:
public class RequestJson extends Request<JSONObject> {
private Listener<JSONObject> listener;
private Map<String, String> params;
public RequestJson(String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
public RequestJson(int method, String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return params;
};
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
AppController.getInstance().checkSessionCookie(response.headers);
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
AppController.getInstance().addSessionCookie(headers);
return headers;
}
}
Hope this will solve your problem.

Related

Post Array using volley

I Want to post something like this [1,2,14,15] using volley to my PHP file where there's a SQL to retreive data from database.
Here my volley :
Map<String, String> userParams = new HashMap<String, String>();
listParams.put(TAG_IDS, all_ids);
CustomRequest myREquest= new CustomRequest(Request.Method.POST, URL, listParams,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
And in my PHP file i'll use a SQL something like this :
$liste=$_POST['IDS'] ;
$val= array_map('intval', $liste);
$new_liste = implode("','", $val);
$query = "SELECT * table WHERE IDS IN('".$new_liste ."')";
Here my CustomRequest
public class CustomRequest extends Request<JSONObject> {
private Response.Listener<JSONObject> listener;
private Map<String, String> params;
public CustomRequest(String url, Map<String, String> params, Response.Listener<JSONObject> reponseListener,
Response.ErrorListener errorListener){
super(Method.GET, url, errorListener);
this.listener=reponseListener;
this.params= params;
}
public CustomRequest(int methode, String url, Map<String, String> params, Response.Listener<JSONObject> reponseListener,
Response.ErrorListener errorListener){
super(methode,url,errorListener);
this.listener = reponseListener;
this.params = params;
}
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError{
return params;
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
}catch (UnsupportedEncodingException e){
return Response.error(new ParseError(e));
}catch (JSONException je){
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
listener.onResponse(response);
}
}
Please help.
You should iterate your all_ids and put all of them in Map which will be send to the server. For example:
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
for(int i=0; i<all_ids.size(); i++) {
params.put(TAG_IDS + "[" + i + "]", all_ids.get(i).toString());
}
return params;
}

Getting 500 error for Volley PUT request android

CustomRequest.java
public class CustomRequest extends Request<JSONObject> {
private Listener<JSONObject> listener;
private Map<String, String> params;
private Map<String, String> headers;
public CustomRequest(String url,
Map<String, String> params,
Map<String, String> headers,
Listener<JSONObject> reponseListener,
ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = reponseListener;
this.params = params;
this.headers = headers;
}
public CustomRequest(int method,
String url,
Map<String, String> params,
Map<String, String> headers,
Listener<JSONObject> reponseListener,
ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
this.headers = headers;
}
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return params;
};
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
I am using request like this in my class:
Map<String, String> params = new HashMap<>();
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
Iterator it = params.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
Log.d(context.getClass().getCanonicalName(), "params - " + pairs.getKey() + ", " + pairs.getValue());
}
String url = AppConstants.SERVER_URL + mApi + "/" + mType+ "/" +mWord.getID();
Log.d("FinalUrl:->", url);
RequestQueue requestQueue = Volley.newRequestQueue(ActDrawAreaTwo.this);
CustomRequest jsObjRequest = new CustomRequest(Request.Method.PUT,
url,
params,
headers,
this.createRequestSuccessListener(),
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progress.dismiss();
}
});
RequestQueueHelper.addToRequestQueue(jsObjRequest, "");
I am getting error:
11-22 10:28:01.605 17921-18491/com.app.admin E/Volley: [3516] BasicNetwork.performRequest: Unexpected response code 500
Its a put request, its working in postman
According to your Postman screenshot, I suggest you use the following sample code:
String url = "http://...";
JSONObject jsonBody;
try {
jsonBody = new JSONObject();
jsonBody.put("ID", 1);
jsonBody.put("Name", "Word1");
jsonBody.put("ArabicName", "Arabic Word1");
// other key-value pairs...
JsonObjectRequest request = new JsonObjectRequest(Request.Method.PUT, url, jsonBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// do something
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something
}
});
queue.add(request);
} catch (JSONException e) {
e.printStackTrace();
}
Hope this helps!

Way to pass Long parameter in url request using volley

Server is not accepting String parameters when making json object request (by post method) using volley, also in custom volley request it is required to pass a string Hash map in getParams() method i am having string as well as long values to be pass over there, Also tried by Uri class but there is also sting is required in appendQueryParameter(). i have used below links Link 1
Link 2 Link 3
Volley class
public class CustomRequest extends Request {
private Listener<JSONObject> listener;
private Map<String, String> params;
public CustomRequest(String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
public CustomRequest(int method, String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return params;
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
/* return Response.success(
gson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response));*/
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
String loginEncoded = new String(Base64.encode(("uictester:?f!T!ziX}.,(").getBytes(), Base64.DEFAULT));
headers.put("Authorization", "Basic " + loginEncoded);
return headers;
}
#Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
}
You first need to convert the long parameter to String using String.valueOf(long value) method and then put this param to the hashmap with its key. as:
params.put("key", String.valueOf(long value));

Add custom headers with Volley library

I start using Volley for my application and I want to add custom headers for each request as a security identifier.
I'm using a JsonObjectRequest and overriding the getHeaders().
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
url,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
String mApiKey = "123";
headers.put("APIKEY", mApiKey);
return headers;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("param1", "1");
params.put("param2", "2");
params.put("param3", "3");
return params;
}
};
VolleySingleton.getInstance(getActivity()).addToRequestQueue(jsonObjectRequest);
But I get this error:
E/Volley﹕ [23620] BasicNetwork.performRequest: Unexpected response code 401 for http://...
The AuthFailureError is thrown.
I also try to use StringRequest but same error.
If someone is in the same case and have solution, thank you in advance!
This is a basic concept how to override a header in a standard VolleyRequest
VolleyRequest networkRequest = new VolleyRequest(request.getHttpMethod(), mUrlBase + request.getUrlSuffix(), responseListener, errorListener) {
public String getBodyContentType() {
return "application/json; charset=" + getParamsEncoding();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> map = new HashMap<String, String>();
map.put("X-Device-Info","Android FOO BAR");
map.put("Accept-Language", acceptLanguage);
map.put("Content-Type", "application/json; charset=UTF-8");
return map;
}
public byte[] getBody() throws AuthFailureError {
try {
String json = request.toJson().toString();
if (json.length() < 3)
return ("{}").getBytes();
// log(json);
return json.getBytes(getParamsEncoding());
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "getBody(): request has no json");
e.printStackTrace();
}
return new byte[0];
}
};
public class CustomJsonObjectRequest extends JsonObjectRequest
{
public CustomJsonObjectRequest(int method, String url, JSONObject jsonRequest,Response.Listener listener, Response.ErrorListener errorListener)
{
super(method, url, jsonRequest, listener, errorListener);
}
#Override
public Map getHeaders() throws AuthFailureError {
Map headers = new HashMap();
headers.put(Constants.accesstoken, Globals.getInstance().getAccessToken());
Logger.debugE(Constants.accesstoken, headers.toString());
return headers;
}
}

Custom basic authentication with Volley?

I am trying create a custom BasicAuthentication with Volley. I have a class ApplicationController that I implemented methods getHeaders and works fine with all application, but now, I have a method that I need send other BasicAuthentication with other Parameters. To do it I am trying #Override the getHeaders() of class ApplicationController. It doesnt works and return a exception.
How can I do it ?
Exception
12-13 20:11:26.300 32356-430/br.com.application.apppackage E/Volley﹕ [157735] BasicNetwork.performRequest: Unexpected response code 400 for http://www.aplication.com.br/ServiceEndpointRest/WsChat/ws/salas/interact.json
12-13 20:11:26.305 32356-32356/br.com.application.apppackage E/ERROR METHOD:﹕ receiveMessage in ChatDAO: null
I'm trying this.
ApplicationController
public class ApplicationController extends Request<JSONObject>{
private Map<String, String> headers;
private Map<String, String> params;
private Response.Listener<JSONObject> listener;
private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
private File mImageFile;
private Map<String, Object> imageParams;
public ApplicationController(String url, Map<String, String> params, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = listener;
this.params = params;
}
public ApplicationController(int method, String url, Map<String, String> params, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = listener;
this.params = params;
}
protected Map<String, String> getParams() throws AuthFailureError {
return params;
};
public Map<String, String> getHeaders() throws AuthFailureError {
headers = new HashMap<String, String>();
String cred = String.format("%s:%s", BasicAuthenticationRest.USERNAME, BasicAuthenticationRest.PASSWORD);
String auth = "Basic " + Base64.encodeToString(cred.getBytes(), Base64.DEFAULT);
headers.put("Authorization", auth);
return headers;
};
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
listener.onResponse(response);
}
}
#Override Header in Method receiveMessage
public ApplicationController receiveMessage(String emailAdversario){
///{\"Sala\":{\"usuario\":\"%#\",\"adversario\":\"%#\",\"atualizacao\":\"%#\",\"device\":\"%#\",\"device_tipo\":\"ios\"}}
urlPost.append("WsChat/ws/salas/interacao.json");
HashMap<String, String> params = new HashMap<String, String>();
params.put("usuario", BatalhaConfigs.USUARIO_EMAIL);
params.put("atualizacao", new Date().toString());
params.put("email", BatalhaConfigs.USUARIO_EMAIL);
params.put("device", AndroidReturnId.getAndroidId());
params.put("device_tipo", "android");
ApplicationController apc = new ApplicationController(Request.Method.POST,
urlPost.toString(),
params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject obj) {
Log.i("RESPOSTA DA MENSAGEM: ", obj.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
Log.e("ERROR METHOD:", "receiveMessage in ChatDAO: " + arg0.getLocalizedMessage());
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
String cred = String.format("%s:%s", BatalhaConfigs.USUARIO_EMAIL, BatalhaConfigs.USUARIO_SENHA);
String auth = "Basic " + Base64.encodeToString(cred.getBytes(), Base64.DEFAULT);
headers.put("Authorization", auth);
return headers;
}};
return apc;
}

Categories

Resources