I'm trying to send a JsonObjectRequest to my server with some params, but seems like params doesn't arrive at the server. Before to post on SO I try all kind of suggestion found in google but no one works fine..
This is the code of my JsonObjectRequest:
RequestQueue queue = MySingleVolley.getInstance(ctx).
getRequestQueue();
JsonObjectRequest jsObjRequest = new JsonObjectRequest(method,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("REQUEST_JSON_TO_SERVER", "Success: " + response.toString());
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("REQUEST_JSON_TO_SERVER", "Error: " + error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
#Override
protected Map<String, String> getParams() {
return params;
}
};
MySingleVolley.getInstance(ctx).addToRequestQueue(jsObjRequest);
And these are my param and others:
String url = "url";
//create the hashMap of parameters
database_zappapp db = new database_zappapp(getApplicationContext());
db.open();
HashMap<String, String> params = new HashMap<>();
params.put("action","myAction");
params.put("nomeutente", db.getUsernameLogged());
params.put("token", token);
db.close();
//Send the request to the server
Global.RequestJsonToServer(getApplicationContext(), url, Request.Method.POST, params);
Thanks in advance for the help!
Edit 2
I've changed my params in this creating a string jsonBody:
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("action","gcmUserRegister");
jsonObject.put("nomeutente",db.getUsernameLogged());
jsonObject.put("token",token);
}catch(JSONException e){
e.printStackTrace();
}
String requestBody = jsonObject.toString();
db.close();
and my request like this with getBody():
JsonObjectRequest jsObjRequest = new JsonObjectRequest(method,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("REQUEST_JSON_TO_SERVER", "Success: " + response.toString());
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("REQUEST_JSON_TO_SERVER", "Error: " + error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
return headers;
}
#Override
public byte[] getBody() {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
requestBody, "utf-8");
return null;
}
}
};
But already didn't work! =(
Postman screen:
No user found means that it enter in the if statement and so it works.. with android i receive "result": "null"
The postman screen with app/json:
I've found the solution!
The problem was in the server not in the client, I was getting the data using POST but from the client I was sending a json object so my new php is:
$data = json_decode(file_get_contents('php://input'), true);
//echo "Action: ".$action;
//Registrazione del token
if($data['action'] == "gcmUserRegister"){
......
Thanks al lot to BKS!!!
Change this part of your code:
`JsonObjectRequest jsObjRequest = new JsonObjectRequest(method,url,null ...`
To this:
`JsonObjectRequest jsObjRequest = new JsonObjectRequest(method,url,yourparams..`
Reason: if you are using the default Volley constructors thats the way to send params to Server.
Related
I'm trying to update a PUT request which has a JSONArray inside it and I'm constantly getting a 500 error response. Here how the api structure is:
{
"imei": 514515854152463,
"franquia": "SAO",
"sistema": "PEGASUS",
"lista": 2055313,
"entregas":[
{
"codHawb": "02305767706",
"dataHoraBaixa": "2020-12-03T15:26:22",
"foraAlvo": 1000,
"latitude": 44.4545,
"longitude": 45.545,
"nivelBateria": 98,
"tipoBaixa": "ENTREGA"
}
]
}
I've tried the api in Postman to see if its working and it is. But when I'm trying it in the program using Volley I'm getting that error. I've tried volley and here is the code:
private void PutJsonRequest() {
try {
Map<String, String> postParam = new HashMap<String, String>();
postParam.put("imei", "514515854152463");
postParam.put("franquia", preferences.getFranchise());
postParam.put("sistema", preferences.getSystem());
postParam.put("lista", preferences.getListID());
postParam.put("dataHoraBaixa", "2020-12-03T15:26:22");
postParam.put("foraAlvo", "100");
postParam.put("latitude", "45.545");
postParam.put("longitude", " 45.554");
postParam.put("nivelBateria", "98");
postParam.put("tipoBaixa", "ENTREGA");
JsonObjectRequest request = new JsonObjectRequest(Request.Method.PUT, ApiUtils.GET_LIST + preferences.getListID(), new JSONObject(postParam), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "PUTonResponse: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "PUTonResponseError: " + error);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
String auth1 = "Basic "
+ Base64.encodeToString((preferences.getUserName() + ":" + preferences.getPass()).getBytes(),
Base64.NO_WRAP);
params.put("Authorization", auth1);
params.put("x-ver", "3.0");
params.put("x-ras", "rick");
params.put("Content-Type", "application/json");
return params;
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
queue.add(request);
} catch (Exception e) {
e.printStackTrace();
}
}
Here is the result in postman:1
Here is the result in postman:2
The problem is there is an array in the api, I've tried the above in the way if there are only JSON object but it is not working, please help me know if anything can be updated or done in different way for sending arrays either in volley or retrofit. Thanks.
//Edit:
I tried sending the params in another way and this was also giving the same 500 error:
JSONArray jsonArray=new JSONArray();
JSONObject jsonObj=new JSONObject();
try {
jsonObj.put("codHawb", "02305767706");
jsonObj.put("dataHoraBaixa", "2020-12-03T15:26:22");
jsonObj.put("foraAlvo", "100");
jsonObj.put("latitude", "-46.86617505263801");
jsonObj.put("longitude", " -23.214458905023452");
jsonObj.put("nivelBateria", "98");
jsonObj.put("tipoBaixa", "ENTREGA");
jsonArray.put(jsonObj);
Map<String, String> postParam = new HashMap<String, String>();
postParam.put("imei", "514515854152463");
postParam.put("franquia", preferences.getFranchise());
postParam.put("sistema", preferences.getSystem());
postParam.put("lista", preferences.getListID());
postParam.put("entregas",jsonArray.toString());
Finally figured it out, sending the PUT request in the form of api. FYI: If you have multiple json objects inside the array, just use a for loop, here is the working answer:
private void PutJsonRequest() {
JSONArray jsonArray=new JSONArray();
JSONObject jsonObj=new JSONObject();
JSONObject jsonObj1=new JSONObject();
try {
jsonObj.put("codHawb", "02305767706");
jsonObj.put("dataHoraBaixa", "2020-12-03T15:26:22");
jsonObj.put("foraAlvo", "100");
jsonObj.put("latitude", "45.222");
jsonObj.put("longitude", " 23.23452");
jsonObj.put("nivelBateria", "98");
jsonObj.put("tipoBaixa", "ENTREGA");
jsonArray.put(jsonObj);
jsonObj1.put("imei", preferences.getIMEI());
jsonObj1.put("franquia", preferences.getFranchise());
jsonObj1.put("sistema", preferences.getSystem());
jsonObj1.put("lista", preferences.getListID());
jsonObj1.put("entregas", jsonArray);
Log.e(TAG, "PutJsonRequest: "+jsonObj1 );
JsonObjectRequest request = new JsonObjectRequest(Request.Method.PUT, ApiUtils.GET_LIST + preferences.getListID(),jsonObj1, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "PUTonResponse: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "PUTonResponseError: " + error);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
String auth1 = "Basic "
+ Base64.encodeToString((preferences.getUserName() + ":" + preferences.getPaso()).getBytes(),
Base64.NO_WRAP);
params.put("Authorization", auth1);
params.put("x-versao-rt", "3.8.10");
params.put("x-rastreador", "ricardo");
// params.put("Content-Type", "application/json");
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
request.setTag(TAG);
queue.add(request);
} catch (Exception e) {
e.printStackTrace();
}
}
Comment if anyone has a doubt.
I'm calling a restful api on my android project and I used Volley and JsonObjectRequest, I thought that the third parameter of the JsonObjectRequest which is jsonRequest are the api parameters so I created a json object for that which in the end I only got errors. So is it common to directly add the api parameters on the url? instead of passing it on a json object? what is the third parameter for, it would be really helpful if someone can give me an example. And my last question is how do you get the entire json response instead of using response.getString("title") for each key.
//api parameters directly added on the url
String URL = "https://www.myapi.com/?param=sample¶m1=sample1";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String title = response.getString("Title");
Log.d("title", title);
} catch(Exception e){
Log.e("response error", e.toString());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.toString());
}
});
Below your Response.ErrorListener() you need to add these two overrides:
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.toString());
}) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("param", "sample");
params.put("param1", "sample1);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/x-www-form-urlencoded; charset=UTF-8");
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
return headers;
}
};
I am currently sending firebase cloud messages from Postman, using an http post request. Its all working fine. I am now trying to make a simple Android app to send the messages from, . However it doesn't work and I get either InvalidRegistration or MissingRegistration or com.android.volley.AuthFailureError
In postman, I do an http post request to https://fcm.googleapis.com/fcm/send
With 2 headers:
Key: 'Authorization' Value: 'key=AAAAnfdQ2jM:AP....'
Key: 'Content-Type' Value: application/json
Then in body, using raw:
{
"to": "/topics/anytopic",
"data": {
"my_message": "Hi everyone!",
}
}
Where and how do I put this information in my volley http post request?
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest sr = new StringRequest(Request.Method.POST,"https://fcm.googleapis.com/fcm/send", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Response: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
return params;
}
};
queue.add(sr);
I can't find any example of this.
Thanks so much.
You need to add a JSON body like this:
JSONObject jsonBody = new JSONObject();
jsonBody.put("to", REUVEN_TOKEN_BE_YOUNG);
JSONObject jsonObject = new JSONObject();
jsonObject.put("my_message", "Keep eating healthy!");
jsonBody.putOpt("data", jsonObject);
final String requestBody = jsonBody.toString();
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest sr = new StringRequest(Request.Method.POST,"https://fcm.googleapis.com/fcm/send", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Response: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "That didn't work..." + error);
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Authorization",BE_YOUNG_APP_KEY);
return params;
}
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
};
queue.add(sr);
From two days i am trying to solve this issue but still i have no any result,why each and every time volley returning me 403 error. where i m wrong? i am using postman to check same webservice, it returns success result. But same thing when i am using in Android via volley or httpurlconnection getting 403 error.kindly help me to find my error.
This is my code which i have tried:
StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST, Constant.posturl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String result=response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse response = error.networkResponse;
int status = response.statusCode;
}
}) {
#Override
public Map<String, String> getHeaders() {
try {
headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
String credentials = Constant.USERNAME + ":" + Constant.PASSWORD;
String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.DEFAULT);
headers.put("Authorization", auth);
return headers;
} catch (Exception e) {
e.printStackTrace();
return headers;
}
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("title", heading_edit_text.getText().toString());
params.put("content", body_edit_text.getText().toString());
params.put("Slug", heading_edit_text.getText().toString());
params.put("date", currentDate);
return params;
}
};
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(50000, 3, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
Volley does provide a proper request for this which is called JsonObjectRequest.
String webAddress = "url here";
RequestQueue queue = Volley.newRequestQueue(this); // singletone here
JSONObject object = new JSONObject();
try {
object.put("title", heading_edit_text.getText().toString());
object.put("content", body_edit_text.getText().toString());
object.put("Slug", heading_edit_text.getText().toString());
object.put("date", currentDate);
} catch (JSONException e) {
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, webAddress,object, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject object) {
Log.d("RESPONSE", object.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d("RESPONSE", "That didn't work!");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> header = new HashMap<>();
// content type is not needed here
header.put("Authorization", "value here");
return header;
}
};
queue.add(request);
Change the "Content-Type" of your headers to "application/form-data"
ie,
headers.put("Content-Type", "application/form-data");
I was also face this issue in news api. But when I use Retrfit its work like a charm.
I can POST Map <String, String> to my server but it comes in & separated form.
I have used code from Send post request using Volley and receive in PHP
getParams() just doesn't work with JSONObject return type. Is it possible to send JSONObject as JSON only?
I want to send data as JSON that I will get using file_get_contents(php://input).
For this I have changed Content-Type to application/json; charset=utf-8.
The problem is using this way I get data in format of x=abc&y=def as it's Map<String, String> type and I want data in JSON format of {"x":"abc", "y":"def"}
It's different from above question because I want to POST data in JSON ONLY and not in MAP of String
Try this :
private void jsonObjReq() {
showProcessDialog();
Map<String, String> postParam= new HashMap<String, String>();
postParam.put("un", "xyz#gmail.com");
postParam.put("p", "somepasswordhere");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Const.URL_LOGIN, new JsonObject(postParam),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
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;
}
};
change header in your php too.
the easy way is this
final RequestQueue requestQueue = Volley.newRequestQueue(this);
final String url ="http://mykulwstc000006.kul/Services/Customer/Register";
Map<String, String> params = new HashMap<String, String>();
params.put("MobileNumber", "+97333765439");
params.put("EmailAddress", "danish.hussain4#das.com");
params.put("FirstName", "Danish2");
params.put("LastName", "Hussain2");
params.put("Country", "BH");
params.put("Language", "EN");
JsonObjectRequest req = new JsonObjectRequest(url, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
}){
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
String username ="eli#gmail.com";
String password = "elie73";
String auth =new String(username + ":" + password);
byte[] data = auth.getBytes();
String base64 = Base64.encodeToString(data, Base64.NO_WRAP);
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization","Basic "+base64);
return headers;
}
};
requestQueue.add(req);
}