requestQueue volley doenst work (sending multiple requests) - android

I want to upload multiple images (using base64 encode).
I send these images using a for :
for(int i =1; i<6; i++){
bmp = ((BitmapDrawable)imgs[i].getDrawable()).getBitmap();
String image = getEncoded64ImageStringFromBitmap(bmp);
SendImage(image);
}
But it just send one or two requests of 5 requests! also no error occurs here. I have a requestQueue that I initialized at onCreate method.
And this is my volley request :
private void SendImage( final String image) {
String URL = APPURL;
final StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new Hashtable<String, String>();
params.put("image", image);
return params;
}
};
{
requestQueue.add(stringRequest);
Toast.makeText(AddProduct.this,"added "+requestQueue.getSequenceNumber(),Toast.LENGTH_SHORT).show();
}}

You have to do this through the recursion method
like
just you have to call one time
multiFileUpload(uploadedFileCount);
then it will process all file in recursion model.
private int totalFileCount = 6;
private int uploadedFileCount = 1;
private String URL = APPURL;
private multiFileUpload(int _uploadedFileCount)
{
final StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if((uploadedFileCount<6)
{
uploadedFileCount++;
multiFileUpload(uploadedFileCount);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Bitmap bmp = ((BitmapDrawable)imgs[_uploadedFileCount].getDrawable()).getBitmap();
String image = getEncoded64ImageStringFromBitmap(bmp);
Map<String, String> params = new Hashtable<String, String>();
params.put("image", image);
return params;
}
};
{
requestQueue.add(stringRequest);
Toast.makeText(AddProduct.this,"added "+requestQueue.getSequenceNumber(),Toast.LENGTH_SHORT).show();
}
}

My problem was at the backend part. The images come at the same time and I used time() function to name them so just one or two file saved in the server.

Related

How to make android Volley request with body like following

I have following request in postman and I want to implement it in volley, android.
Any solution?
following is request header
Following is request body
Do like this .Add headers data like this.
RequestQueue queue = Volley.newRequestQueue(this);
String url = APICLient.BASE_URL+"api/Admin_controller/getProspectField";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jo=new JSONObject(response);
Boolean status=jo.getBoolean("success");
JSONArray ja=jo.getJSONArray("user");
// write your logic here...
for (int i=0;i<ja.length();i++){
JSONObject jsonObject=ja.getJSONObject(i);
String pname=jsonObject.getString("p_name");
String pType=jsonObject.getString("p_type");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}) {
#Override
public Map<String, String> getHeaders(){
HashMap <String,String> params=new HashMap<>();
params.put("authorization","put_authorization_key_here");
return params;
}
#Override
public Map<String, String> getParams(){
HashMap <String,String> params=new HashMap<>();
params.put("care_team[]",team);
........................
return params;
}
};
queue.add(stringRequest);
Hope this will work.
Json Parsing with volley:
private void userLogin() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting response to json object
JSONObject obj = new JSONObject(response);
//if no error in response
if (obj.getBoolean("status")) {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
User user = new User(
userJson.getInt("cid"),
userJson.getInt("company_id"),
userJson.getString("name"),
userJson.getString("email")
);
//storing the user in shared preferences
SharedPreferenceManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
} catch (JSONException e) {
e.printStackTrace();
progressBar.setVisibility(View.GONE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("company_id",companyid );
params.put("email", username);
params.put("password", password);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("x-api-key", "swicons#1019");
return headers;
}
};
stringRequest.setShouldCache(false);
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}

POST Request in Volley(using JSON instead of String)

I am developing an app in which i find the origin and destination of a car and send it to a server.
I know how to use volley to send an string however i am finding it hard to send data in JSON format.
Part of the code is given below:
b
tnFindPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RequestQueue queue = Volley.newRequestQueue(MapsActivity.this);
String url = "http://192.168.43.162:8080/";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
//adding parameters to the request
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("origin", etOrigin.getText().toString());
params.put("destination", etDestination.getText().toString());
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
try this
final String httpUrl = //your url
try {
JSONArray parameters = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put(Key,value);
jsonObject.put(Key,value);
parameters.put(jsonObject);
Log.i(TAG,parameters.toString());
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, httpUrl, parametersForPhp,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG,response.toString());
try {
//your code
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
RequestQueueSingleton.getInstance(getApplicationContext()).addToRequestQueue(arrayRequest);
}catch (Exception e){
e.printStackTrace();
}
}

Nodejs req.body shows empty from Android Volley

Android Code:
private void registerUser(){
final String username = "subrata";
final String password = "banerjee";
final String email = "test_email";
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_USERNAME,username);
params.put(KEY_PASSWORD,password);
params.put(KEY_EMAIL, email);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
I'm trying to send http request using Android Volley to my node.js server (expressjs). Its hitting the server and getting the response but when I'm printing the req.body in node.js its shows {} (empty). I'm new to Android and unable to figure out the reason. Please someone guide me.
Call this method in OnResponse GetResponse(response);
And the method will be
private void GetResponse(String res){
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(res);
JSONArray result = jsonObject.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject jo = result.getJSONObject(i);
String temp = jo.getString("what_ever");
String temp1 = jo.getString("what_ever_1");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
This will get you the response in String format fetched from json.
private void registerUser(){
JSONObject jsonBodyObj = new JSONObject();
try{
jsonBodyObj.put("mAtt", "+1");
jsonBodyObj.put("mDatum","+2");
jsonBodyObj.put("mRID","+3");
jsonBodyObj.put("mVon","+4");
}catch (JSONException e){
e.printStackTrace();
}
final String requestBody = jsonBodyObj.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#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");
headers.put("User-agent", "My useragent");
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;
}
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}

How to send a POST request using volley with string body?

I'm developing an Android app that communicate with a RESTful web service I wrote. Using Volley for GET methods is awesome and easy, but I can't put my finger on the POST methods.
I want to send a POST request with a String in the body of the request, and retrieve the raw response of the web service (like 200 ok, 500 server error).
All I could find is the StringRequest which doesn't allow to send with data (body), and also it bounds me to receive a parsed String response.
I also came across JsonObjectRequest which accepts data (body) but retrieve a parsed JSONObject response.
I decided to write my own implementation, but I cannot find a way to receive the raw response from the web service. How can I do it?
You can refer to the following code (of course you can customize to get more details of the network response):
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
JSONObject jsonBody = new JSONObject();
jsonBody.put("Title", "Android Volley Demo");
jsonBody.put("Author", "BNK");
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#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;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
I liked this one, but it is sending JSON not string as requested in the question, reposting the code here, in case the original github got removed or changed, and this one found to be useful by someone.
public static void postNewComment(Context context,final UserAccount userAccount,final String comment,final int blogId,final int postId){
mPostCommentResponse.requestStarted();
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.POST,"http://api.someservice.com/post/comment", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mPostCommentResponse.requestCompleted();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mPostCommentResponse.requestEndedWithError(error);
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("user",userAccount.getUsername());
params.put("pass",userAccount.getPassword());
params.put("comment", Uri.encode(comment));
params.put("comment_post_ID",String.valueOf(postId));
params.put("blogId",String.valueOf(blogId));
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
queue.add(sr);
}
public interface PostCommentResponseListener {
public void requestStarted();
public void requestCompleted();
public void requestEndedWithError(VolleyError error);
}
Name = editTextName.getText().toString().trim();
Email = editTextEmail.getText().toString().trim();
Phone = editTextMobile.getText().toString().trim();
JSONArray jsonArray = new JSONArray();
jsonArray.put(Name);
jsonArray.put(Email);
jsonArray.put(Phone);
final String mRequestBody = jsonArray.toString();
StringRequest stringRequest = new StringRequest(Request.Method.PUT, OTP_Url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.v("LOG_VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG_VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
};
stringRequest.setShouldCache(false);
VollySupport.getmInstance(RegisterActivity.this).addToRequestque(stringRequest);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("Rest response",response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Rest response",error.toString());
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String,String>();
params.put("name","xyz");
return params;
}
#Override
public Map<String,String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String,String>();
params.put("content-type","application/fesf");
return params;
}
};
requestQueue.add(stringRequest);
I created a function for a Volley Request. You just need to pass the arguments :
public void callvolly(final String username, final String password){
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = "http://your_url.com/abc.php"; // <----enter your post url here
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("username", username);
MyData.put("password", password);
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
}

Android Volley POST JsonObject and get JsonArray or JsonObject or Other response

in volley we have some ability to retrieve data from server such as jsonObject,jsonArray and String. in this below sample we can get simply jsonObject or jsonArray response from server,
public static void POST(HashMap<String, String> params, final Listeners.ServerResponseListener listener) {
JsonObjectRequest req1 = new JsonObjectRequest(ApplicationController.URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("Response:", response.toString());
if (listener != null)
listener.onResultJsonObject(response);
else
Log.e(TAG,"Error: SetServerResponse interface not set");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error: ", error.getMessage());
}
});
ApplicationController.getInstance().addToRequestQueue(req1);
}
my problem is i want to send jsonObject from this method and get jsonArray or jsonObject from server, and i can not get simply array from server with this method. for example i must be filter server response with this jsonObject:
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "AbCdEfGh123456");
params.put("search_count", "10");
params.put("order_by", "id");
server return jsonArray and i can not get that with Volley response
Looking at the source code of JsonArrayRequest. There is a constructor which takes in a JSONObject. You should check it out
public class RetreiveData {
public static final String TAG = RetreiveData.class.getSimpleName();
public static void POST(String localhost, final HashMap<String, String> params, final Listeners.ServerResponseListener listener) {
StringRequest post = new StringRequest(Request.Method.POST, localhost, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
if (listener != null)
listener.onResponse(response.toString());
else
Log.e(TAG, "Error: SetServerResponse interface not set");
} catch (Exception e) {
e.printStackTrace();
Log.d("Error: ", e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error: ", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = params;
return map;
}
#Override
public RetryPolicy getRetryPolicy() {
setRetryPolicy(new DefaultRetryPolicy(
5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
return super.getRetryPolicy();
}
};
ApplicationController.getInstance().addToRequestQueue(post);
}
}

Categories

Resources