I've been using the volley library for consuming services with my android app. I noticed something weird,when I try to post a json object to server, I have to make a response Listener of type JSONObject. But my server returns a String, Success or failure. Is it possible to write a JsonObjectRequest which waits for a String response? this is What I have written. The service runs correctly, but the onErrorResponse is triggered after successful post due to cannot converge String to JSON
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, jsonBody,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(StartingActivity.this,response.toString(),Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(StartingActivity.this,"That didn't work",Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(jsonRequest);
Use StringRequest instead of JsonObjectRequest. it will return response in string Like this:
StringRequest stringRequest = new StringRequest(Request.Method.POST,url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG,response);
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
//use this to post data.
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
//use this for headers.
}
};
stringRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 50000;
}
#Override
public int getCurrentRetryCount() {
return 50000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
The jsonBody your sending to server it should be in String.
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, jsonBody.toString(),
I hope this will help you. Thanks!
Related
private void postRequest() {
// Request a string response from the provided URL.
// Instantiate the RequestQueue.
String url = "http://10.0.0.9:3000/hello";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
Log.i("*********", "******");
response.put("Hello", "World");
}catch(JSONException e){
Log.i("JSONERROR", e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
Log.i("*********", error.toString());
}
});
jsonObjectRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 1000;
}
#Override
public int getCurrentRetryCount() {
return 1000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
});
This is the Android code
app.post('/hello', function(req,res){
console.log(JSON.stringify(req.body))
})
This is the node js code
So the problem im having is that im printing the body to the console but it keeps showing up empty. As you can see in the postRequest method ive put 'hello as key' and 'world as value' in the jsonobject. So it is calling the correct post request, the body is just empty and cant figure out why that is.
Edit-----
Ive checked the content with wireshark and content length is 0 so im not sending anything it seems. if im understanding this correctly
You are not sending anything inside of your POST body request, that's why you are getting an empty response at your server-side.
For sending POST parameters, you will need to override getParams() method:
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
map.put("param1", "hello");
map.put("param2", "This is a post request");
return map;
}
Here is the complete example:
private void postRequest() {
// Request a string response from the provided URL.
// Instantiate the RequestQueue.
String url = "http://10.0.0.9:3000/hello";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
Log.i("*********", "******");
response.put("Hello", "World");
}catch(JSONException e){
Log.i("JSONERROR", e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
Log.i("*********", error.toString());
}
}) { // HERE TO ADD POST PARAMETERS
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
map.put("param1", "hello");
map.put("param2", "This is a post request");
return map;
}
};
jsonObjectRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 1000;
}
#Override
public int getCurrentRetryCount() {
return 1000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
});
I'm going to send a JsonObjectRequest to the server as form-data using Volley Library. I Checked similar questions. none of them covers my problem.
This is Postman ScreenShot of the exact request that I need:
This is My JSONObject named myKey which contains a JSONArray:
{
"myArray":[
{
"code":"FA95",
"id":"94"
}
]
}
and this is my request method:
public static void getSomething(String url) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public byte[] getBody() {
return super.getBody();
}
};
request.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(request);
}
Should I override getBody() or not? and what should it return exactly?
Here is the answer: https://stackoverflow.com/a/39718240/3024933
You need to override the getParams() method and use StringRequest instead of JsonObjectRequest.
i want to asking about request in android. I made a request, but when executed, it stores 2 data in the database. I have no idea why this doesn't work well.
For information, i use php to handle request. and not only on my web apps. When i try using another web apps, it still save 2 data.
this is my code, thanks.
public void sendToServer(){
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest URL = new StringRequest(Request.Method.POST, storeCC, new Response.Listener<String>(){
#Override
public void onResponse(String response) {
Log.d("SUKSES", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error gan", error.toString());
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("poin", point);
jsonParams.put("id_imei",id_imei);
jsonParams.put("billingNm", name);
jsonParams.put("harga", String.valueOf(amt));
return jsonParams;
}
};
RequestHandler.getInstance(this).addToRequestQueue(URL);
}
Hope you help me.
Your problem may arise if you use "https".Add Handler over there and delay the request as Https often response late, Caution you have to manage every request.
Handler handler= new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Your code after 5 seconds delay
sendToServer();
}
},5000);
Try this solution where setRetryPolicy of Volley Request:-
public void sendToServer(){
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, storeCC, new Response.Listener<String>(){
#Override
public void onResponse(String response) {
Log.d("SUKSES", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error gan", error.toString());
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("poin", point);
jsonParams.put("id_imei",id_imei);
jsonParams.put("billingNm", name);
jsonParams.put("harga", String.valueOf(amt));
return jsonParams;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(5*1000,-1,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestHandler.getInstance(this).addToRequestQueue(stringRequest);
}
I have to make a json post request with the following parameters.
{"method":"login","data":{"username":"korea","password":"123456"}}
I use volley to make post request and follwoing is my code to do post request.
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, loginURL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(mContext,response.toString(),Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = new HashMap<String,String>();
map.put("method","login");
map.put("username","korea");
map.put("password","123456");
return map;
}
};
requestQueue.add(jsonObjectRequest);
requestQueue.start();
Im getting error response from server. How to get proper response from server?
Change Request.Method.GET to Request.Method.POST. Then pass a JSONObject as the third parameter where you currently have null;
For example:
JSONObject data = new JSONObject();
data.put("username","korea");
data.put("password","123456");
JSONObject jsonObject = new JSONObject();
jsonObject.put("method","login");
jsonObject.put("data",data);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, loginURL, jsonObject, responseListener, errorListener);
I use volley to make post request and follwoing is my code to do post request
That is not a POST request, AFAICT. You are using Request.Method.GET.
Use following method to post the data to server
public void postDataVolley(Context context,String url,JSONObject sendObj){
try {
RequestQueue queue = Volley.newRequestQueue(context);
JsonObjectRequest jsonObj = new JsonObjectRequest(url,sendObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Volley", "Volley JSON post" + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Volley", "Volley JSON post" + "That didn't work!");
}
});
queue.add(jsonObj);
}catch(Exception e){
}
}
I want to send post request with raw string rather than setting params using volley.
I have tried to override the getBody method in StringRequest like following:
#Override
public byte[] getBody() throws AuthFailureError {
return rawString.getBytes();
}
It won't even send the request and gives the error: com.android.volley.TimeoutError
Any help will be appreciated.
I got so ...
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(myReq);
...
StringRequest myReq = new StringRequest(Request.Method.POST,
server+"Login",
createMyReqSuccessListener(),
createMyReqErrorListener()) {
#Override
public byte[] getBody() throws com.android.volley.AuthFailureError {
String str = "{\"login\":\""+login+"\",\"password\":\""+pass+"\"}";
return str.getBytes();
};
public String getBodyContentType()
{
return "application/json; charset=utf-8";
}
};
...
private Response.Listener<String> createMyReqSuccessListener() {
return new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i(TAG,"Ski data from server - "+response);
}
};
}
private Response.ErrorListener createMyReqErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG,"Ski error connect - "+error);
}
};
}