Related
I want to send three parameters "guestEmail", "latitude" and "longitude" to backend and get a message of success from backend if it is successful.
I have tried doing this:
public void myGetFunc()
{
final String url = "....";
// prepare the Request
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
// display response
Log.d("Response", response.toString());
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", response);
}
}
)
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String> ();
params.put("guestEmail", "abc#xyz.com");
params.put("latitude", "12");
params.put("longitude", "12");
return params;
}
};
// add it to the RequestQueue
queue.add(getRequest);
}
This method is invoked when the 'SOS' button is clicked.
But right now, nothing happens on clicking the 'SOS' button.
Please help!
If you are going to use GET you query parameters and build the string yourself
private static final String URL = "http://www.test.com?value1={val1}&value2={val2}";
String requestString = URL;
requestString.replace("{val1}", "1");
requestString.replace("{val2}", "Bob");
StringRequest strreq = new StringRequest(Request.Method.GET,
requestString,
new Response.Listener<String>() {
#Override
public void onResponse(String Response) {
// get response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError e) {
e.printStackTrace();
}
});
Volley.getInstance(this).addToRequestQueue(strreq);
If you are going to use POST us a body
public class LoginRequest extends Request<String> {
// ... other methods go here
private Map<String, String> mParams;
public LoginRequest(String param1, String param2, Listener<String> listener, ErrorListener errorListener) {
super(Method.POST, "http://test.url", errorListener);
mListener = listener;
mParams = new HashMap<String, String>();
mParams.put("paramOne", param1);
mParams.put("paramTwo", param2);
}
#Override
public Map<String, String> getParams() {
return mParams;
}
}
If you want to pass parameters than you need to use POST method otherwise for GET , just pass values in URL itself.
I saw Google IO 2013 session about Volley and I'm considering switching to volley. Does Volley support adding POST/GET parameters to request? If yes, how can I do it?
For the GET parameters there are two alternatives:
First: As suggested in a comment bellow the question you can just use String and replace the parameters placeholders with their values like:
String uri = String.format("http://somesite.com/some_endpoint.php?param1=%1$s¶m2=%2$s",
num1,
num2);
StringRequest myReq = new StringRequest(Method.GET,
uri,
createMyReqSuccessListener(),
createMyReqErrorListener());
queue.add(myReq);
where num1 and num2 are String variables that contain your values.
Second: If you are using newer external HttpClient (4.2.x for example) you can use URIBuilder to build your Uri. Advantage is that if your uri string already has parameters in it it will be easier to pass it to the URIBuilder and then use ub.setQuery(URLEncodedUtils.format(getGetParams(), "UTF-8")); to add your additional parameters. That way you will not bother to check if "?" is already added to the uri or to miss some & thus eliminating a source for potential errors.
For the POST parameters probably sometimes will be easier than the accepted answer to do it like:
StringRequest myReq = new StringRequest(Method.POST,
"http://somesite.com/some_endpoint.php",
createMyReqSuccessListener(),
createMyReqErrorListener()) {
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("param1", num1);
params.put("param2", num2);
return params;
};
};
queue.add(myReq);
e.g. to just override the getParams() method.
You can find a working example (along with many other basic Volley examples) in the Andorid Volley Examples project.
In your Request class (that extends Request), override the getParams() method. You would do the same for headers, just override getHeaders().
If you look at PostWithBody class in TestRequest.java in Volley tests, you'll find an example.
It goes something like this
public class LoginRequest extends Request<String> {
// ... other methods go here
private Map<String, String> mParams;
public LoginRequest(String param1, String param2, Listener<String> listener, ErrorListener errorListener) {
super(Method.POST, "http://test.url", errorListener);
mListener = listener;
mParams = new HashMap<String, String>();
mParams.put("paramOne", param1);
mParams.put("paramTwo", param2);
}
#Override
public Map<String, String> getParams() {
return mParams;
}
}
Evan Charlton was kind enough to make a quick example project to show us how to use volley.
https://github.com/evancharlton/folly/
CustomRequest is a way to solve the Volley's JSONObjectRequest can't post parameters like the StringRequest
here is the helper class which allow to add params:
import java.io.UnsupportedEncodingException;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
public class CustomRequest extends Request<JSONObject> {
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));
} 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);
}
}
thanks to Greenchiu
This helper class manages parameters for GET and POST requests:
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
public class CustomRequest extends Request<JSONObject> {
private int mMethod;
private String mUrl;
private Map<String, String> mParams;
private Listener<JSONObject> mListener;
public CustomRequest(int method, String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.mMethod = method;
this.mUrl = url;
this.mParams = params;
this.mListener = reponseListener;
}
#Override
public String getUrl() {
if(mMethod == Request.Method.GET) {
if(mParams != null) {
StringBuilder stringBuilder = new StringBuilder(mUrl);
Iterator<Map.Entry<String, String>> iterator = mParams.entrySet().iterator();
int i = 1;
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
if (i == 1) {
stringBuilder.append("?" + entry.getKey() + "=" + entry.getValue());
} else {
stringBuilder.append("&" + entry.getKey() + "=" + entry.getValue());
}
iterator.remove(); // avoids a ConcurrentModificationException
i++;
}
mUrl = stringBuilder.toString();
}
}
return mUrl;
}
#Override
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return mParams;
};
#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
mListener.onResponse(response);
}
}
Dealing with GET parameters I iterated on Andrea Motto' solution.
The problem was that Volley called GetUrl several times and his solution, using an Iterator, destroyed original Map object. The subsequent Volley internal calls had an empty params object.
I added also the encode of parameters.
This is an inline usage (no subclass).
public void GET(String url, Map<String, String> params, Response.Listener<String> response_listener, Response.ErrorListener error_listener, String API_KEY, String stringRequestTag) {
final Map<String, String> mParams = params;
final String mAPI_KEY = API_KEY;
final String mUrl = url;
StringRequest stringRequest = new StringRequest(
Request.Method.GET,
mUrl,
response_listener,
error_listener
) {
#Override
protected Map<String, String> getParams() {
return mParams;
}
#Override
public String getUrl() {
StringBuilder stringBuilder = new StringBuilder(mUrl);
int i = 1;
for (Map.Entry<String,String> entry: mParams.entrySet()) {
String key;
String value;
try {
key = URLEncoder.encode(entry.getKey(), "UTF-8");
value = URLEncoder.encode(entry.getValue(), "UTF-8");
if(i == 1) {
stringBuilder.append("?" + key + "=" + value);
} else {
stringBuilder.append("&" + key + "=" + value);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
String url = stringBuilder.toString();
return url;
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
if (!(mAPI_KEY.equals(""))) {
headers.put("X-API-KEY", mAPI_KEY);
}
return headers;
}
};
if (stringRequestTag != null) {
stringRequest.setTag(stringRequestTag);
}
mRequestQueue.add(stringRequest);
}
This function uses headers to pass an APIKEY and sets a TAG to the request useful to cancel it before its completion.
Hope this helps.
This may help you...
private void loggedInToMainPage(final String emailName, final String passwordName) {
String tag_string_req = "req_login";
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://localhost/index", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
Boolean error = jsonObject.getBoolean("error");
if (!error) {
String uid = jsonObject.getString("uid");
JSONObject user = jsonObject.getJSONObject("user");
String email = user.getString("email");
String password = user.getString("password");
session.setLogin(true);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
Toast.makeText(getApplicationContext(), "its ok", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
System.out.println("volley Error .................");
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("email", emailName);
params.put("password", passwordName);
return params;
}
};
MyApplication.getInstance().addToRequestQueue(stringRequest,tag_string_req);
}
For Future Readers
I love to work with Volley. To save development time i tried to write small handy library Gloxey Netwok Manager to setup Volley with my project. It includes JSON parser and different other methods that helps to check network availability.
Use ConnectionManager.class in which different methods for Volley String and Volley JSON request are available.
You can make requests of GET, PUT, POST, DELETE with or without header. You can read full documentation here.
Just put this line in your gradle file.
dependencies {
compile 'io.gloxey.gnm:network-manager:1.0.1'
}
Volley StringRequest
Method GET (without header)
ConnectionManager.volleyStringRequest(context, isDialog, progressDialogView, requestURL, volleyResponseInterface);
How to use?
Configuration Description
Context Context
isDialog If true dialog will appear, otherwise not.
progressView For custom progress view supply your progress view id and make isDialog true. otherwise pass null.
requestURL Pass your API URL.
volleyResponseInterface Callback for response.
Example
ConnectionManager.volleyStringRequest(this, false, null, "url", new VolleyResponse() {
#Override
public void onResponse(String _response) {
/**
* Handle Response
*/
}
#Override
public void onErrorResponse(VolleyError error) {
/**
* handle Volley Error
*/
}
#Override
public void isNetwork(boolean connected) {
/**
* True if internet is connected otherwise false
*/
}
});
Volley StringRequest
Method POST/PUT/DELETE (without header)
ConnectionManager.volleyStringRequest(context, isDialog, progressDialogView, requestURL, requestMethod, params, volleyResponseInterface);
Example
Use Method : Request.Method.POST
Request.Method.PUT
Request.Method.DELETE
Your params :
HashMap<String, String> params = new HashMap<>();
params.put("param 1", "value");
params.put("param 2", "value");
ConnectionManager.volleyStringRequest(this, true, null, "url", Request.Method.POST, params, new VolleyResponse() {
#Override
public void onResponse(String _response) {
/**
* Handle Response
*/
}
#Override
public void onErrorResponse(VolleyError error) {
/**
* handle Volley Error
*/
}
#Override
public void isNetwork(boolean connected) {
/**
* True if internet is connected otherwise false
*/
}
});
Bonus
Gloxey JSON Parser
Feel free to use gloxey json parser to parse your api response.
YourModel yourModel = GloxeyJsonParser.getInstance().parse(stringResponse, YourModel.class);
Example
ConnectionManager.volleyStringRequest(this, false, null, "url", new VolleyResponse() {
#Override
public void onResponse(String _response) {
/**
* Handle Response
*/
try {
YourModel yourModel = GloxeyJsonParser.getInstance().parse(_response, YourModel.class);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onErrorResponse(VolleyError error) {
/**
* handle Volley Error
*/
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
showSnackBar(parentLayout, getString(R.string.internet_not_found), getString(R.string.retry), new View.OnClickListener() {
#Override
public void onClick(View view) {
//handle retry button
}
});
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ServerError) {
} else if (error instanceof NetworkError) {
} else if (error instanceof ParseError) {
}
}
#Override
public void isNetwork(boolean connected) {
/**
* True if internet is connected otherwise false
*/
if (!connected) {
showSnackBar(parentLayout, getString(R.string.internet_not_found), getString(R.string.retry), new View.OnClickListener() {
#Override
public void onClick(View view) {
//Handle retry button
}
});
}
});
public void showSnackBar(View view, String message) {
Snackbar.make(view, message, Snackbar.LENGTH_LONG).show();
}
public void showSnackBar(View view, String message, String actionText, View.OnClickListener onClickListener) {
Snackbar.make(view, message, Snackbar.LENGTH_LONG).setAction(actionText, onClickListener).show();
}
To provide POST parameter send your parameter as JSONObject in to the JsonObjectRequest constructor. 3rd parameter accepts a JSONObject that is used in Request body.
JSONObject paramJson = new JSONObject();
paramJson.put("key1", "value1");
paramJson.put("key2", "value2");
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url,paramJson,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
I am using android Volley for making a request. So I use this code. I don't understand one thing. I check in my server that params is always null. I consider that getParams() not working. What should I do to solve this issue.
RequestQueue queue = MyVolley.getRequestQueue();
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,SPHERE_URL,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response);
hideProgressDialog();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideProgressDialog();
}
}) {
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("id","1");
params.put("name", "myname");
return params;
};
};
queue.add(jsObjRequest);
try to use this helper class
import java.io.UnsupportedEncodingException;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
public class CustomRequest extends Request<JSONObject> {
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));
} 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);
}
}
In activity/fragment do use this
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
CustomRequest jsObjRequest = new CustomRequest(Method.POST, url, params, this.createRequestSuccessListener(), this.createRequestErrorListener());
requestQueue.add(jsObjRequest);
You can create a custom JSONObjectReuqest and override the getParams method, or you can provide them in the constructor as a JSONObject to be put in the body of the request.
Like this (I edited your code):
JSONObject obj = new JSONObject();
obj.put("id", "1");
obj.put("name", "myname");
RequestQueue queue = MyVolley.getRequestQueue();
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,SPHERE_URL,obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response);
hideProgressDialog();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideProgressDialog();
}
});
queue.add(jsObjRequest);
Easy one for me ! I got it few weeks ago :
This goes in getBody() method, not in getParams() for a post request.
Here is mine :
#Override
/**
* Returns the raw POST or PUT body to be sent.
*
* #throws AuthFailureError in the event of auth failure
*/
public byte[] getBody() throws AuthFailureError {
// Map<String, String> params = getParams();
Map<String, String> params = new HashMap<String, String>();
params.put("id","1");
params.put("name", "myname");
if (params != null && params.size() > 0) {
return encodeParameters(params, getParamsEncoding());
}
return null;
}
(I assumed you want to POST the params you wrote in your getParams)
I gave the params to the request inside the constructor, but since you are creating the request on the fly, you can hard coded them inside your override of the getBody() method.
This is what my code looks like :
Bundle param = new Bundle();
param.putString(HttpUtils.HTTP_CALL_TAG_KEY, tag);
param.putString(HttpUtils.HTTP_CALL_PATH_KEY, url);
param.putString(HttpUtils.HTTP_CALL_PARAM_KEY, params);
switch (type) {
case RequestType.POST:
param.putInt(HttpUtils.HTTP_CALL_TYPE_KEY, RequestType.POST);
SCMainActivity.mRequestQueue.add(new SCRequestPOST(Method.POST, url, this, tag, receiver, params));
and if you want even more this last string params comes from :
param = JsonUtils.XWWWUrlEncoder.encode(new JSONObject(paramasJObj)).toString();
and the paramasJObj is something like this : {"id"="1","name"="myname"} the usual JSON string.
When you working with JsonObject request you need to pass the parameters right after you pass the link in the initialization , take a look on this code :
HashMap<String, String> params = new HashMap<>();
params.put("user", "something" );
params.put("some_params", "something" );
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, "request_URL", new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Some code
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//handle errors
}
});
}
All you need to do is to override getParams method in Request class. I had the same problem and I searched through the answers but I could not find a proper one. The problem is unlike get request, post parameters being redirected by the servers may be dropped. For instance, read this. So, don't risk your requests to be redirected by webserver. If you are targeting http://example/myapp , then mention the exact address of your service, that is http://example.com/myapp/index.php.
Volley is OK and works perfectly, the problem stems from somewhere else.
The override function getParams works fine. You use POST method and you have set the jBody as null. That's why it doesn't work. You could use GET method if you want to send null jBody.
I have override the method getParams and it works either with GET method (and null jBody) either with POST method (and jBody != null)
Also there are all the examples here
I had the same issue once, the empty POST array is caused due a redirection of the request (on your server side), fix the URL so it doesn't have to be redirected when it hits the server. For Example, if https is forced using the .htaccess file on your server side app, make sure your client request has the "https://" prefix. Usually when a redirect happens the POST array is lost. I Hope this helps!
It worked for can try this for calling with Volley Json Request and Response ith Java Code .
public void callLogin(String sMethodToCall, String sUserId, String sPass) {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST, ConstantValues.ROOT_URL_LOCAL + sMethodToCall.toString().trim(), addJsonParams(sUserId, sPass),
// JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, object,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("onResponse", response.toString());
Toast.makeText(VolleyMethods.this, response.toString(), Toast.LENGTH_LONG).show(); // Test
parseResponse(response);
// msgResponse.setText(response.toString());
// hideProgressDialog();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("onErrorResponse", "Error: " + error.getMessage());
Toast.makeText(VolleyMethods.this, error.toString(), Toast.LENGTH_LONG).show();
// hideProgressDialog();
}
}) {
/**
* Passing some request headers
*/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
requestQueue.add(jsonObjectRequest);
}
public JSONObject addJsonParams(String sUserId, String sPass) {
JSONObject jsonobject = new JSONObject();
try {
// {"id":,"login":"secretary","password":"password"}
///***//
Log.d("addJsonParams", "addJsonParams");
// JSONObject jsonobject = new JSONObject();
// JSONObject jsonobject_one = new JSONObject();
//
// jsonobject_one.put("type", "event_and_offer");
// jsonobject_one.put("devicetype", "I");
//
// JSONObject jsonobject_TWO = new JSONObject();
// jsonobject_TWO.put("value", "event");
// JSONObject jsonobject = new JSONObject();
//
// jsonobject.put("requestinfo", jsonobject_TWO);
// jsonobject.put("request", jsonobject_one);
jsonobject.put("id", "");
jsonobject.put("login", sUserId); // sUserId
jsonobject.put("password", sPass); // sPass
// js.put("data", jsonobject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonobject;
}
public void parseResponse(JSONObject response) {
Boolean bIsSuccess = false; // Write according to your logic this is demo.
try {
JSONObject jObject = new JSONObject(String.valueOf(response));
bIsSuccess = jObject.getBoolean("success");
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(VolleyMethods.this, "" + e.toString(), Toast.LENGTH_LONG).show(); // Test
}
}
build gradle(app)
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.1.0'
implementation 'androidx.appcompat:appcompat:1.1.0-alpha01'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.android.volley:volley:1.1.1'
}
android manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
MainActivity
When you use JsonObjectRequest it is mandatory to send a jsonobject and receive jsonobject otherwise you will get an error as it only accepts jsonobject.
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
fun peticion(){
val jsonObject = JSONObject()
jsonObject.put("user", "jairo")
jsonObject.put("password", "1234")
val queue = Volley.newRequestQueue(this)
val url = "http://192.168.0.3/get_user.php"
// GET: JsonObjectRequest( url, null,
// POST: JsonObjectRequest( url, jsonObject,
val jsonObjectRequest = JsonObjectRequest( url, jsonObject,
Response.Listener { response ->
// Check if the object 'msm' does not exist
if(response.isNull("msm")){
println("Name: "+response.getString("nombre1"))
}
else{
// If the object 'msm' exists we print it
println("msm: "+response.getString("msm"))
}
},
Response.ErrorListener { error ->
error.printStackTrace()
println(error.toString())
}
)
queue.add(jsonObjectRequest)
}
file php get_user.php
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
// we receive the parameters
$json = file_get_contents('php://input');
$params = json_decode($json);
error_reporting(0);
require_once 'conexion.php';
$mysqli=getConex();
$user=$params->user;
$password=$params->password;
$res=array();
$verifica_usuario=mysqli_query($mysqli,"SELECT * FROM usuarios WHERE usuario='$user' and clave='$password'");
if(mysqli_num_rows($verifica_usuario)>0){
$query="SELECT * FROM usuarios WHERE usuario='$user'";
$result=$mysqli->query($query);
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$res=$row;
}
}
else{
$res=array('msm'=>"Incorrect user or password");
}
$jsonstring = json_encode($res);
header('Content-Type: application/json');
echo $jsonstring;
?>
file php conexion
<?php
function getConex(){
$servidor="localhost";
$usuario="root";
$pass="";
$base="db";
$mysqli = mysqli_connect($servidor,$usuario,$pass,$base);
if (mysqli_connect_errno($mysqli)){
echo "Fallo al conectar a MySQL: " . mysqli_connect_error();
}
$mysqli->set_charset('utf8');
return $mysqli;
}
?>
I'm currently trying to send a simple POST-request via Google Volley to my server.
Therefore I've written the following lines of code:
Map<String, String> params = new HashMap<String, String>();
params.put("regId", "skdjasjdaljdlksajskl");
JSONObject object = new JSONObject(params);
JsonObjectRequest request = new JsonObjectRequest(Method.POST,
"address_of_my_server/method", object,
successListener, errorListener);
queue.add(request);
But I get an Error 500 returned, which says, that there is a missing parameter (regId). I've tried the same with a GET-Request, but I got the same result.
Only when I'm using a StringRequest with a formatted URL like "address_of_my_server/method?regId=sadlasjdlasdklsj" the server replies with 200.
I get the exact same result when I use a StringRequest like:
StringRequest request = new StringRequest(Method.POST,
"myurl", successListener,
errorListener){
#Override
protected Map<String, String> getParams()
throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("regId", "skdjasjdaljdlksajskl");
return params;
}
};
Why is Volley ignoring my parameters?
I had same issue last week, but it is fixed now.
Your server accepts the Content-Type as form-data, when sending volley's JsonObjectRequest the request's content-type will be application/json so whole params will be sent as one json body, not as key value pairs as in Stringrequest.
Change the server code to get request params from http request body instead of getting it from keys(like $_REQUEST['name'] in php).
Use this helper class:
import java.io.UnsupportedEncodingException;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
public class CustomRequest extends Request<JSONObject> {
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));
} 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);
}
}
Woking example with the issue that Rajesh Batth mentioned
Java code:
JSONObject obj = new JSONObject();
try {
obj.put("id", "1");
obj.put("name", "myname");
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsObjRequest = new JsonObjectRequest(
Request.Method.POST, url, obj, listener, errorlistener);
RequestQueue queue = Volley.newRequestQueue(context);
queue.add(jsObjRequest);
PHP-Code:
$body = file_get_contents('php://input');
$postvars = json_decode($body, true);
$id = $postvars["id"];
$name = $postvars["name"];
Note:
The PHP-Vars $_POST and $_REQUEST and $_GET are empty if you are not sending additional GET-VARS.
EDIT:
I deleted my previous answer since it wasn't accurate.
I'll go over what I know today:
Apparently, getParams should work. But it doesn't always.
I have debugged it myself, and it seems that it is being called when performing a PUT or POST request, and the params provided in that method are in a regular GET parameters string (?param1=value1¶m2=value2...) and encoded and put in the body.
I don't know why but for some reason this doesn't work for some servers.
The best alternate way I know to send parameters, is to put your parameters in a JSONObject and encode its contents in the request's body, using the request constructor.
Thi's my solution
Solution 1
public void getData() {
final RequestQueue queue = Volley.newRequestQueue(this);
StringRequest postRequest = new StringRequest(Request.Method.POST, "192.168.0.0/XYZ",new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray myArray = new JSONArray(response);
for(int i = 0; i < myArray.length(); i++)
{
JSONObject jObj = myArray.getJSONObject(i);
String category = jObj.getString("nameUser");
Log.e("value", category);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("error: ", e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(context,"Error : ").show();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id_user", "1");
return params;
}
};
queue.add(postRequest);
}
Solution 2
remember that if you use php,the $_POST[''];
not working, her more information.
Good Luck
I saw Google IO 2013 session about Volley and I'm considering switching to volley. Does Volley support adding POST/GET parameters to request? If yes, how can I do it?
For the GET parameters there are two alternatives:
First: As suggested in a comment bellow the question you can just use String and replace the parameters placeholders with their values like:
String uri = String.format("http://somesite.com/some_endpoint.php?param1=%1$s¶m2=%2$s",
num1,
num2);
StringRequest myReq = new StringRequest(Method.GET,
uri,
createMyReqSuccessListener(),
createMyReqErrorListener());
queue.add(myReq);
where num1 and num2 are String variables that contain your values.
Second: If you are using newer external HttpClient (4.2.x for example) you can use URIBuilder to build your Uri. Advantage is that if your uri string already has parameters in it it will be easier to pass it to the URIBuilder and then use ub.setQuery(URLEncodedUtils.format(getGetParams(), "UTF-8")); to add your additional parameters. That way you will not bother to check if "?" is already added to the uri or to miss some & thus eliminating a source for potential errors.
For the POST parameters probably sometimes will be easier than the accepted answer to do it like:
StringRequest myReq = new StringRequest(Method.POST,
"http://somesite.com/some_endpoint.php",
createMyReqSuccessListener(),
createMyReqErrorListener()) {
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("param1", num1);
params.put("param2", num2);
return params;
};
};
queue.add(myReq);
e.g. to just override the getParams() method.
You can find a working example (along with many other basic Volley examples) in the Andorid Volley Examples project.
In your Request class (that extends Request), override the getParams() method. You would do the same for headers, just override getHeaders().
If you look at PostWithBody class in TestRequest.java in Volley tests, you'll find an example.
It goes something like this
public class LoginRequest extends Request<String> {
// ... other methods go here
private Map<String, String> mParams;
public LoginRequest(String param1, String param2, Listener<String> listener, ErrorListener errorListener) {
super(Method.POST, "http://test.url", errorListener);
mListener = listener;
mParams = new HashMap<String, String>();
mParams.put("paramOne", param1);
mParams.put("paramTwo", param2);
}
#Override
public Map<String, String> getParams() {
return mParams;
}
}
Evan Charlton was kind enough to make a quick example project to show us how to use volley.
https://github.com/evancharlton/folly/
CustomRequest is a way to solve the Volley's JSONObjectRequest can't post parameters like the StringRequest
here is the helper class which allow to add params:
import java.io.UnsupportedEncodingException;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
public class CustomRequest extends Request<JSONObject> {
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));
} 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);
}
}
thanks to Greenchiu
This helper class manages parameters for GET and POST requests:
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
public class CustomRequest extends Request<JSONObject> {
private int mMethod;
private String mUrl;
private Map<String, String> mParams;
private Listener<JSONObject> mListener;
public CustomRequest(int method, String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.mMethod = method;
this.mUrl = url;
this.mParams = params;
this.mListener = reponseListener;
}
#Override
public String getUrl() {
if(mMethod == Request.Method.GET) {
if(mParams != null) {
StringBuilder stringBuilder = new StringBuilder(mUrl);
Iterator<Map.Entry<String, String>> iterator = mParams.entrySet().iterator();
int i = 1;
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
if (i == 1) {
stringBuilder.append("?" + entry.getKey() + "=" + entry.getValue());
} else {
stringBuilder.append("&" + entry.getKey() + "=" + entry.getValue());
}
iterator.remove(); // avoids a ConcurrentModificationException
i++;
}
mUrl = stringBuilder.toString();
}
}
return mUrl;
}
#Override
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return mParams;
};
#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
mListener.onResponse(response);
}
}
Dealing with GET parameters I iterated on Andrea Motto' solution.
The problem was that Volley called GetUrl several times and his solution, using an Iterator, destroyed original Map object. The subsequent Volley internal calls had an empty params object.
I added also the encode of parameters.
This is an inline usage (no subclass).
public void GET(String url, Map<String, String> params, Response.Listener<String> response_listener, Response.ErrorListener error_listener, String API_KEY, String stringRequestTag) {
final Map<String, String> mParams = params;
final String mAPI_KEY = API_KEY;
final String mUrl = url;
StringRequest stringRequest = new StringRequest(
Request.Method.GET,
mUrl,
response_listener,
error_listener
) {
#Override
protected Map<String, String> getParams() {
return mParams;
}
#Override
public String getUrl() {
StringBuilder stringBuilder = new StringBuilder(mUrl);
int i = 1;
for (Map.Entry<String,String> entry: mParams.entrySet()) {
String key;
String value;
try {
key = URLEncoder.encode(entry.getKey(), "UTF-8");
value = URLEncoder.encode(entry.getValue(), "UTF-8");
if(i == 1) {
stringBuilder.append("?" + key + "=" + value);
} else {
stringBuilder.append("&" + key + "=" + value);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
String url = stringBuilder.toString();
return url;
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
if (!(mAPI_KEY.equals(""))) {
headers.put("X-API-KEY", mAPI_KEY);
}
return headers;
}
};
if (stringRequestTag != null) {
stringRequest.setTag(stringRequestTag);
}
mRequestQueue.add(stringRequest);
}
This function uses headers to pass an APIKEY and sets a TAG to the request useful to cancel it before its completion.
Hope this helps.
This may help you...
private void loggedInToMainPage(final String emailName, final String passwordName) {
String tag_string_req = "req_login";
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://localhost/index", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
Boolean error = jsonObject.getBoolean("error");
if (!error) {
String uid = jsonObject.getString("uid");
JSONObject user = jsonObject.getJSONObject("user");
String email = user.getString("email");
String password = user.getString("password");
session.setLogin(true);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
Toast.makeText(getApplicationContext(), "its ok", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
System.out.println("volley Error .................");
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("email", emailName);
params.put("password", passwordName);
return params;
}
};
MyApplication.getInstance().addToRequestQueue(stringRequest,tag_string_req);
}
For Future Readers
I love to work with Volley. To save development time i tried to write small handy library Gloxey Netwok Manager to setup Volley with my project. It includes JSON parser and different other methods that helps to check network availability.
Use ConnectionManager.class in which different methods for Volley String and Volley JSON request are available.
You can make requests of GET, PUT, POST, DELETE with or without header. You can read full documentation here.
Just put this line in your gradle file.
dependencies {
compile 'io.gloxey.gnm:network-manager:1.0.1'
}
Volley StringRequest
Method GET (without header)
ConnectionManager.volleyStringRequest(context, isDialog, progressDialogView, requestURL, volleyResponseInterface);
How to use?
Configuration Description
Context Context
isDialog If true dialog will appear, otherwise not.
progressView For custom progress view supply your progress view id and make isDialog true. otherwise pass null.
requestURL Pass your API URL.
volleyResponseInterface Callback for response.
Example
ConnectionManager.volleyStringRequest(this, false, null, "url", new VolleyResponse() {
#Override
public void onResponse(String _response) {
/**
* Handle Response
*/
}
#Override
public void onErrorResponse(VolleyError error) {
/**
* handle Volley Error
*/
}
#Override
public void isNetwork(boolean connected) {
/**
* True if internet is connected otherwise false
*/
}
});
Volley StringRequest
Method POST/PUT/DELETE (without header)
ConnectionManager.volleyStringRequest(context, isDialog, progressDialogView, requestURL, requestMethod, params, volleyResponseInterface);
Example
Use Method : Request.Method.POST
Request.Method.PUT
Request.Method.DELETE
Your params :
HashMap<String, String> params = new HashMap<>();
params.put("param 1", "value");
params.put("param 2", "value");
ConnectionManager.volleyStringRequest(this, true, null, "url", Request.Method.POST, params, new VolleyResponse() {
#Override
public void onResponse(String _response) {
/**
* Handle Response
*/
}
#Override
public void onErrorResponse(VolleyError error) {
/**
* handle Volley Error
*/
}
#Override
public void isNetwork(boolean connected) {
/**
* True if internet is connected otherwise false
*/
}
});
Bonus
Gloxey JSON Parser
Feel free to use gloxey json parser to parse your api response.
YourModel yourModel = GloxeyJsonParser.getInstance().parse(stringResponse, YourModel.class);
Example
ConnectionManager.volleyStringRequest(this, false, null, "url", new VolleyResponse() {
#Override
public void onResponse(String _response) {
/**
* Handle Response
*/
try {
YourModel yourModel = GloxeyJsonParser.getInstance().parse(_response, YourModel.class);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onErrorResponse(VolleyError error) {
/**
* handle Volley Error
*/
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
showSnackBar(parentLayout, getString(R.string.internet_not_found), getString(R.string.retry), new View.OnClickListener() {
#Override
public void onClick(View view) {
//handle retry button
}
});
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ServerError) {
} else if (error instanceof NetworkError) {
} else if (error instanceof ParseError) {
}
}
#Override
public void isNetwork(boolean connected) {
/**
* True if internet is connected otherwise false
*/
if (!connected) {
showSnackBar(parentLayout, getString(R.string.internet_not_found), getString(R.string.retry), new View.OnClickListener() {
#Override
public void onClick(View view) {
//Handle retry button
}
});
}
});
public void showSnackBar(View view, String message) {
Snackbar.make(view, message, Snackbar.LENGTH_LONG).show();
}
public void showSnackBar(View view, String message, String actionText, View.OnClickListener onClickListener) {
Snackbar.make(view, message, Snackbar.LENGTH_LONG).setAction(actionText, onClickListener).show();
}
To provide POST parameter send your parameter as JSONObject in to the JsonObjectRequest constructor. 3rd parameter accepts a JSONObject that is used in Request body.
JSONObject paramJson = new JSONObject();
paramJson.put("key1", "value1");
paramJson.put("key2", "value2");
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url,paramJson,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);