GET Request parameters using Volley - android

I'm making an Android App that integrates with the Facebook API and uses a REST API, so I'm using Volley. However, I'm trying to issue a GET request for a JSON Array, and have to include the Facebook Authorization token in order to access the server. Most of the questions I've seen on this are relatively old, and it seems like Volley now provides support to pass in request params (from the volley github page):
/**
* Creates a new request.
* #param method the HTTP method to use
* #param url URL to fetch the JSON from
* #param jsonRequest A {#link JSONArray} 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 JsonArrayRequest(int method, String url, JSONArray jsonRequest,
Listener<JSONArray> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
}
But when I make and issue a JsonArrayRequest, I get a com.android.volley.AuthFailureError. Here is my code, does anyone know what I'm doing wrong?
#Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println("Yo im here");
JSONObject requestParams = new JSONObject();
JSONArray paramArray = new JSONArray();
try {
requestParams.put("Authorization", "JWT (Facebook auth token)");
paramArray.put(requestParams);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(paramArray.toString());
RequestQueue queue = Volley.newRequestQueue(this);
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET,
GET_MAP_MICS,
paramArray,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray micArray) {
try {
for (int i = 0; i < micArray.length(); i++) {
JSONObject jsonobject = micArray.getJSONObject(i);
int micId = jsonobject.getInt("micId");
String status = jsonobject.getString("status");
System.out.println("Good so far!");
double venLat = jsonobject.getDouble("venueLat");
double venLong = jsonobject.getDouble("venueLat");
System.out.println("got here, check it: " + venLat);
}
}catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError e) {
System.out.println(e);
}
});

GET method don't take parameters only POSTwill
in your case your passing Headers as body for GET method you have pass headers
JsonObjectRequest request = new JsonObjectRequest(url, (JSONObject) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
/*Add your headers here*/
return super.getHeaders();
}
};
final possibility there is two same class name will be there in your project for example any lib your using also using volley lib this happens once for me

Related

Android Volley POST Parameters

I need to call an api that expects a string array as a POST parameter. So for an example of an API definition:
POST api/names
POST parameter expected is an array of names and some other attributes like below:
{ names: [ "John", "Bill" ], department: "Engineering" }
I am currently using a custom Volley framework as described in the Android documentation but it seems like the parameters from Volley can only be passed as a Map of (String, String as key and value). I already have the array from my Android app, ready to be passed as a post parameter but this Volley expects a String.
I tried to convert my array using Arrays.toString(myStringArray) and passed it like below but it does not work.
String[] namesArray = new String[1];
namesArray[0] = "Bill";
Map<String, String> mapParams = new HashMap<String, String>();
mapParams.put("department", "Computer Science");
mapParams.put("names", Arrays.toString(namesArray));
// Then call the Volley here passing the mapParams.
How can I call the api that expects a String of array when I can only use a String from Volley?
I will give you full code to post JsonObject on volley, through POST method.
JSONObject js = new JSONObject();
try {
js.put("genderType", "MALE");
}
} catch (JSONException e) {
e.printStackTrace();
}
String url = "LINK TO POST/";
// Make request for JSONObject
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.POST, url, js,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Response_Code from Volley" + "\n" + response.toString() + " i am king");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e(TAG, "Error: " + error.getMessage());
NetworkResponse response = error.networkResponse;
if (error instanceof ServerError && response != null) {
try {
String res = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, "utf-8"));
// Now you can use any deserializer to make sense of data
Log.e(TAG, "onErrorResponse: of uploadUser" + res);
// JSONObject obj = new JSONObject(res);
} catch (UnsupportedEncodingException e1) {
// Couldn't properly decode data to string
e1.printStackTrace();
}
}
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
};
Log.e(TAG, "uploadUser: near volley new request ");
// Adding request to request queue
Volley.newRequestQueue(this).add(jsonObjReq);
}
Put anything you need in the js object with key and its values
Use JsonObjectRequest and simply pass a JSONObject. There's a full example here
public void makePostRequest(final Map<String,String> myMap,String MEDIA_URL,final VolleyResponse callback)
{
VolleySingleton VS;
Log.e("URL",MEDIA_URL);
VS=VS.getInstance();
RequestQueue rq=VS.getRequestQueue();
StringRequest stringRequest = new StringRequest(Request.Method.POST,MEDIA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
callback.onSuccess(s);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
callback.onError();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new Hashtable<String, String>();
Iterator<Map.Entry<String, String>> iterator = myMap.entrySet().iterator();
while(iterator.hasNext()) {
Map.Entry<String,String> pairs = (Map.Entry<String,String>)iterator.next();
String value = pairs.getValue();
String key = pairs.getKey();
params.put(key,value);
Log.e("Key","Value"+value);
}
return params;
}
};
//Creating a Request Queue
// RequestQueue requestQueue = Volley.newRequestQueue(this);
DefaultRetryPolicy retryPolicy = new DefaultRetryPolicy(0, -1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(retryPolicy);
//Adding request to the queue
rq.add(stringRequest);
}
Where the VolleyResponse is a simple custom interface like this
public interface VolleyResponse {
void onSuccess(String resp);
void onError();
}

Using Volley Library in android in a structured pattern

I am using Volley to make network calls in my application... For many screens ...(say fragments) I am making various requests like LoginRequest, FetchUsers Request, FetchExams Request..... and handling response and errors in each fragments.
What is the best approach I can use like....
1. Subclass a request
2. Create an interface/callbacks
3. Get results/response or error response in my fragment...
This is how I am doing ....creating many such methods.....
private void syncAllUsers() {
progressDialog.setMessage("Loading Users...");
StringRequest jsonProductCategoryFetchRequest = new StringRequest(Request.Method.POST, Config.SELECT_USERS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
if(Constants.DEBUG_MODE_ON)
Log.d(Constants.DEBUG_LOG, "RESPONSE for Teachers: "+response);
JSONObject result = new JSONObject(response);
boolean code = result.getBoolean("error");
if (!code) {
//Get the Users Json Array
JSONArray ja = result.getJSONArray("users");
if(ja != null) {
db.deleteAllUsers();
for (int i = 0; i < ja.length(); i++) {
JSONObject jobj = ja.getJSONObject(i);
User user = new User();
user.setId(jobj.getInt(User.KEY_ID));
user.setName(jobj.getString(User.KEY_NAME));
user.setEmail(jobj.getString(User.KEY_EMAIL));
user.setPhone(jobj.getString(User.KEY_PHONE));
user.setGender(jobj.getString(User.KEY_GENDER));
user.setUsername(jobj.getString(User.KEY_USERNAME));
user.setPassword(jobj.getString(User.KEY_PASSWORD));
user.setOrganization_id(jobj.getString(User.KEY_ORGANIZATION_ID));
user.setDob(jobj.getString(User.KEY_DOB));
user.setStatus(jobj.getString(User.KEY_STATUS));
user.setApi_key(jobj.getString(User.KEY_API_KEY));
user.setDate_created(jobj.getString(User.KEY_DATE_CREATED));
user.setRole_id(jobj.getInt(User.KEY_ROLE_ID));
//Delete local Teachers before updating
db.createUser(user);
} // for loop ends
}
}
//syncAllExams();
progressDialog.dismiss();
getActivity().finish();
startActivity(new Intent(getActivity(), MainActivity.class));
} catch (Exception e) {
Log.d(Constants.DEBUG_LOG, "Exception Syncing Users: " , e);
Toast.makeText(getActivity(),"Something went wrong while fetching users", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
getActivity().finish();
startActivity(new Intent(getActivity(), MainActivity.class));
}
}
} , new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(Constants.DEBUG_MODE_ON)
Log.d(Constants.DEBUG_LOG, "Error Response for Users : "+error.getCause()+""+error.toString());
Toast.makeText(getActivity(), getString(R.string.no_internet), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
getActivity().finish();
startActivity(new Intent(getActivity(), MainActivity.class));
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(User.KEY_ORGANIZATION_ID, preferencesManager.getOrganizationID());
params.put(User.KEY_API_KEY, preferencesManager.getApiKey());
Log.d("Registration", "PARAMS : " + params.entrySet());
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
// params.put("Content-Type", "application/json; charset=utf-8");
params.put("Content-Type", "application/x-www-form-urlencoded");
String auth = preferencesManager.getApiKey();
params.put("Authorization", auth);
return params;
}
};
MyApplication.getInstance().addToReqQueue(jsonProductCategoryFetchRequest);
}
I think there would be a clean way to perform this. Any suggestions.
I have been using this class for creating requests, it transforms your json into your object automaticaly with gson. Find example here:
https://gist.github.com/ficusk/5474673
Create Request Manager.. Which is only dealing with Requesting your web services. That Manager should also handle any network error and other errors which are not application layer.
Use this request manager from your Model classes where your business logic is. Send Request Parameter as JSON.. Also you can send your different listeners from to Request Manager So that when web service response comes it directly comes to you Model class and you can parse JSON response according to your needs.
This way parsing logic stays with Model class and Requesting logic stays with Request manager.. So in future if you change web service address you need to check only one place.. And if you change request and response parameter for webservice you dont need to change request manager and only Model class...
There might be some other ways..
public final class RequestManager {
private static final String ROOT_HOST = //Your Webservice Host Root.
private RequestQueue queue;
public RequestManager(final Context context) {
queue = Volley.newRequestQueue(context);
}
//Internal Calling method .. Not exposed..
private void doRequest(final int method, final String url, final JSONObject jsonParam, final Response.Listener<JSONObject> listener,
final Response.ErrorListener errlsn) {
JSONObjectRequest jsonObjectRequest = new SONObjectRequest(method, url, jsonParam, listener, errlsn);
queue.add(jsonObjectRequest);
}
public void doLogin(final User user, final Response.Listener<JSONObject> listener, final Response.ErrorListener errlsn)
throws Exception {
// Make login request JSON here
if (user == null || listener == null || errlsn == null) {
//throw Exception
}
final JSONObject jsonObj = new JSONObject();
//Convert user object to JSON Object
doRequest(Request.Method.GET, LOGIN_URL, jsonObj, listener, errlsn);
}
}

How to format POST parameters using Volley JSONObjectRequest [duplicate]

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

Volley JsonObjectRequest Post parameters no longer work

I am trying to send POST parameters in a Volley JsonObjectRequest. Initially, it was working for me by following what the official code says to do of passing a JSONObject containing the parameters in the constructor of the JsonObjectRequest. Then all of a sudden it stopped working and I haven't made any changes to the code that was previously working. The server no longer recognizes that any POST parameters are being sent. Here is my code:
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://myserveraddress";
// POST parameters
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "test");
JSONObject jsonObj = new JSONObject(params);
// Request a json response from the provided URL
JsonObjectRequest jsonObjRequest = new JsonObjectRequest
(Request.Method.POST, url, jsonObj, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
});
// Add the request to the RequestQueue.
queue.add(jsonObjRequest);
Here is the simple tester PHP code on the server:
$response = array("tag" => $_POST["tag"]);
echo json_encode($response);
The response I get is {"tag":null}
Yesterday, it worked fine and was responding with {"tag":"test"}
I haven't changed a single thing, but today it is no longer working.
In the Volley source code constructor javadoc it says that you can pass a JSONObject in the constructor to send post parameters at "#param jsonRequest":
https://android.googlesource.com/platform/frameworks/volley/+/master/src/main/java/com/android/volley/toolbox/JsonObjectRequest.java
/**
* 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.
I have read other posts with similar questions, but the solutions haven't worked for me:
Volley JsonObjectRequest Post request not working
Volley Post JsonObjectRequest ignoring parameters while using getHeader and getParams
Volley not sending a post request with parameters.
I've tried setting the JSONObject in the JsonObjectRequest constructor to null, then overriding and setting the parameters in the "getParams()", "getBody()", and "getPostParams()" methods, but none of those overrides has worked for me. Another suggestion was to use an additional helper class that basically creates a custom request, but that fix is a bit too complex for my needs. If it comes down to it I will do anything to make it work, but I am hoping that there is a simple reason as to why my code was working, and then just stopped, and also a simple solution.
You just have to make a JSONObject from your HashMap of parameters:
String url = "https://www.youraddress.com/";
Map<String, String> params = new HashMap();
params.put("first_param", 1);
params.put("second_param", 2);
JSONObject parameters = new JSONObject(params);
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, parameters, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//TODO: handle success
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
//TODO: handle failure
}
});
Volley.newRequestQueue(this).add(jsonRequest);
I ended up using Volley's StringRequest instead, because I was using too much valuable time trying to make JsonObjectRequest work.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://myserveraddress";
StringRequest strRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "test");
return params;
}
};
queue.add(strRequest);
This worked for me. Its just as simple as JsonObjectRequest, but uses a String instead.
I had a similar problem, but I found out that the problem was not on the client side, but in the server side. When you send a JsonObject, you need to get the POST object like this (in the server side):
In PHP:
$json = json_decode(file_get_contents('php://input'), true);
You can use StringRequest to do the same things you can wtih JsonObjectRequest, while still beeing able to easily send POST parameters. The only thing you have to do is to create a JsonObject out of the request String you get, and from there you can continue as if it were JsonObjectRequest.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//Creating JsonObject from response String
JSONObject jsonObject= new JSONObject(response.toString());
//extracting json array from response string
JSONArray jsonArray = jsonObject.getJSONArray("arrname");
JSONObject jsonRow = jsonArray.getJSONObject(0);
//get value from jsonRow
String resultStr = jsonRow.getString("result");
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parameters = new HashMap<String,String>();
parameters.put("parameter",param);
return parameters;
}
};
requestQueue.add(stringRequest);
Use CustomJsonObjectRequest helper class mentioned here.
and implement like this -
CustomJsonObjectRequest request = new CustomJsonObjectRequest(Method.POST, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error.", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("id", id);
params.put("password", password);
return params;
}
};
VolleySingleton.getInstance().addToRequestQueue(request);
Using the JSONObject object to send parameters means the parameters will be in JSON format in the HTTP POST request body :
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "test");
params.put("tag2", "test2");
JSONObject jsonObj = new JSONObject(params);
Will create this JSON object and insert it into the body of the HTTP POST request:
{"tag":"test","tag2":"test2"}
Then the server must decode the JSON to understand these POST parameters.
But normally HTTP POST paramaters are write in the body like:
tag=test&tag2=test2
But NOW here the question is why Volley is set in this manner?
A server reading a HTTP POST method should by standard always try to read parameters also in JSON (other than in plain text) and so a server that does not accomplish is a bad server?
Or instead a HTTP POST body with parameters in JSON is not what normally a server want?
Might help someone and save you some time thinking.
I had a similar issue, the server code was looking for the Content-Type header. It was doing it this way:
if($request->headers->content_type == 'application/json' ){ //Parse JSON... }
But Volley was sending the header like this:
'application/json; charset?utf-8'
Changing the server code to this did the trick:
if( strpos($request->headers->content_type, 'application/json') ){ //Parse JSON...
I had similar problem. But I found out that the problem was not on the server side, but the problem is about cache. You have to clear your RequestQueue Cache.
RequestQueue requestQueue1 = Volley.newRequestQueue(context);
requestQueue1.getCache().clear();
You can do it this way:
CustomRequest request = new CustomRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Toast.makeText(SignActivity.this, response.toString(), Toast.LENGTH_SHORT).show();
Log.d("response",""+response.toString());
String status = response.optString("StatusMessage");
String actionstatus = response.optString("ActionStatus");
Toast.makeText(SignActivity.this, ""+status, Toast.LENGTH_SHORT).show();
if(actionstatus.equals("Success"))
{
Intent i = new Intent(SignActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
dismissProgress();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SignActivity.this, "Error."+error.toString(), Toast.LENGTH_SHORT).show();
Log.d("response",""+error.toString());
dismissProgress();
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Email", emailval);
params.put("PassWord", passwordval);
params.put("FirstName", firstnameval);
params.put("LastName", lastnameval);
params.put("Phone", phoneval);
return params;
}
};
AppSingleton.getInstance(SignActivity.this.getApplicationContext()).addToRequestQueue(request, REQUEST_TAG);
as per CustomRequest below link
Volley JsonObjectRequest Post request not working
It does work.
I parsed json object response using this:-
works like a charm.
String tag_string_req = "string_req";
Map<String, String> params = new HashMap<String, String>();
params.put("user_id","CMD0005");
JSONObject jsonObj = new JSONObject(params);
String url="" //your link
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, jsonObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("responce", response.toString());
try {
// Parsing json object response
// response will be a json object
String userbalance = response.getString("userbalance");
Log.d("userbalance",userbalance);
String walletbalance = response.getString("walletbalance");
Log.d("walletbalance",walletbalance);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
AppControllerVolley.getInstance().addToRequestQueue(jsonObjReq, tag_string_req);
It worked for me can try this for calling with Volley for Json type request and response .
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
}
}
Hope am not too late to the party:
The issue is from the server side. If you are using PHP add the following lines at the top of your php api file (after includes)
$inputJSON = file_get_contents('php://input');
if(get_magic_quotes_gpc())
{
$param = stripslashes($inputJSON);
}
else
{
$param = $inputJSON;
}
$input = json_decode($param, TRUE);
Then to retrieve your values
$tag= $input['tag'];
Use GET in place of POST for using JsonObjectRequest
VolleySingleton.getInstance()
.add(new StringRequest(Request.Method.POST, urlToTest, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// do stuff...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// exception
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() {
return ServerApi.getRequiredParamsRequest(context);
}
}
);
...Initially, it was working for me
....Then all of a sudden it stopped working and I haven't made any changes to
the code
if you haven't made any changes to a previously working code then I suggest checking other parameters such as URL , as the IP address may change if you are using your own Computer as a server!

Send ByteArray with Android volley

There is any way to send a byte array with Volley?
Now I'm using this:
post.setEntity(new ByteArrayEntity(rawPacket.toByteArray()));
try {
response = client.execute(post);
} catch (IOException e) {
e.printStackTrace();
}
There is something like this in Volley? There is a method to pass custom object to send with the POST/GET request?
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
params.put("RawPacket", rawPacket.toByteArray().toString());
return params;
}
I need something like protected Map<String, ByteArray> getParams()
I find the solution overriding the function public byte[] getBody() to send custom data, I should read better the documentation!
StringRequest stringRequest = new StringRequest(Request.Method.POST, "https://www.example.com/",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
return new byte[] {1, 2, 3, 4, 5};
}
See code below:
public class JsonArrayRequest extends JsonRequest<JSONArray> {
/**
* Creates a new request.
* #param url URL to fetch the JSON from
* #param listener Listener to receive the JSON response
* #param errorListener Error listener, or null to ignore errors.
*/
public JsonArrayRequest(String url, Listener<JSONArray> listener, ErrorListener errorListener) {
super(Method.GET, url, null, listener, errorListener);
}
You have to create a subclass of JsonRequest and use that instead.
See related link:
Volley - Sending a POST request using JSONArrayRequest
Also might want to Base64 encode the bytes and add it to the JsonArray.

Categories

Resources