How to get Volley POST response body? - java

I am using simmilar fucntion for creating GET and POST api requests, but the GET function set textview to response body and I dont know how to read the status code and the POST function set textview to the response code and I dont know how to read response body. Can you help me, please?
I also tried to log in parseNetworkResponse() response.data.toString() but thats is not the data that api returns. Maybe I need to encode it somehow?
public void createGet(Context context, String url) {
final TextView apiResultTextview = (TextView) ((Activity)
context).findViewById(R.id.api_result_textview);
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(context);
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
apiResultTextview.setText("Response is: " + response.substring(0, 50));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
apiResultTextview.setText(error.toString());
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
public void createPost(Context context, String url, JSONObject body) {
final TextView apiResultTextview = (TextView) ((Activity) context).findViewById(R.id.api_result_textview);
RequestQueue requestQueue = Volley.newRequestQueue(context);
final String mRequestBody = body.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("LOG_RESPONSE", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG_RESPONSE", 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;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
apiResultTextview.setText("Response is: " + responseString);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
}

I solved it by changing method for call to code below. Problem was probably in JsonObjectRequest vs StringRequest. That's why I was getting only response code string.
public void createCall(int type, String url, JSONObject data, final int callback) {
JsonObjectRequest jsonRequest = new JsonObjectRequest(type, url,data,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
try {
callback(response, callback);
} catch (Exception e){
Log.d("API callback error", e.getMessage());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error response", error.toString());
}
}
);
queue.add(jsonRequest);
}

add this code in you onResponse() Method
JSONObject jsonObj = new JSONObject(response);
String response_value = jsonObj.getString("response");

Related

How to start onResponse method after getParams has been executed with StringRequest in Android Studio Volley?

I am trying to start an JSONArrayRequests after the StringRequest has finished. The StringRequest is POST requet and the JSONArrayRequest is GET request. I want the JSONArray to start when the params of the String is uploaded so as I will be able to retrieve this data again. Below is my code:
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
StringRequest stringRequest = new StringRequest(Request.Method.POST, JSON_URL_UPLOAD_IMAGE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
if (response.equals("1")) {
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.GET, JSON_URL, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0;i<response.length();i++) {
try {
JSONObject object = response.getJSONObject(i);
String USER_ID = object.getString("user_id");
String POST_DATE = object.getString("post_date");
if (USER_ID.equalsIgnoreCase(CurrentUser)){
Toast.makeText(getContext(), "First if.", Toast.LENGTH_SHORT).show();
if (POST_DATE.equalsIgnoreCase(dateTime)) {
Toast.makeText(getContext(), "Second if.", Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley Error", error.getMessage());
}
});
requestQueue.add(arrayRequest);
requestQueue.start();
}
}catch (Exception e) {
e.printStackTrace();
Log.d("ERROR", e.getMessage().toString());
Toast.makeText(getContext(), "ERROR:"+e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Nullable
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("post_author", CurrentUser);
if (!details.getText().toString().equalsIgnoreCase("")){
params.put("post_content", details.getText().toString());
params.put("post_excerpt", details.getText().toString());
}else {
params.put("post_content", "");
params.put("post_excerpt", "");
}
params.put("post_date", dateTime);
params.put("post_date_gmt", dateTime);
params.put("post_title", CurrentUser+"-"+CurrentUser+"-"+timeStampStr);
params.put("post_status", "publish");
params.put("comment_status", "closed");
params.put("ping_status", "closed");
params.put("post_name", CurrentUser+"-"+CurrentUser+"-"+timeStampStr);
params.put("post_modified", dateTime);
params.put("post_modified_gmt", dateTime);
params.put("guid", "https://www.selfcial.com/peepso-post/"+CurrentUser+"-"+CurrentUser+"-"+timeStampStr+"/");
params.put("post_type", "peepso-post");
return params;
}
};
requestQueue.add(stringRequest);
requestQueue.start();
What I tried to do is to add a RequestQueue in order to make the requests wait until the other one is finished but it didn't work. The problem I have is that when the inside request starts it doesn't find the "if" statement(namely this:(USER_ID.equals(CurrentUser) && POST_DATE.equals(dateTime)). So, what I can understand is that the second starts before the first has finished with the params. What can I do? Any answer will be appreciated!

How to Post raw data using volley

My API working correctly but when i send data using android app its not inserting data.
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { JSONObject jsonBody = new JSONObject();
try {
`jsonBody.put("ID", "Android Volley Demo");
jsonBody.put("Name", "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;
}
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
That is my API.Its working correctly.
public HttpResponseMessage Post([FromBody]Login log)
{
db.Logins.Add(log);
db.SaveChanges();
var message = Request.CreateResponse(HttpStatusCode.Created, log);
message.Headers.Location = new Uri(Request.RequestUri + log.ID.ToString());
return message;
}
This is my Code i am Posting data but not inserting in SQL Server but when i test API by sending raw data its working correctly.
Try this:
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String ServerResponse) {
Log.i("VOLLEY Response : ", ServerResponse);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("VOLLEY ErrorResponse : ", volleyError.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Name", "BNK");
return params;
}
};
// Creating RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(context);
// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);
Check this one
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
JSONObject jsonBody = new JSONObject();
jsonBody.put("firstkey", "firstvalue");
jsonBody.put("secondkey", "secondobject");
final String mRequestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("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;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}

How to create a single volley webservice class to use across the android app?

My android application uses multiple network calls in a single activity and i have several of these activities where i have to use both post and get requests. I want to create a single "VolleyWebservice" class and call the same in multiple activities instead of writing the complete volley code. I am relatively new to android development and i don't understand where i am going wrong.
public class VolleyWebService {
public JSONObject result;
public JSONObject getResponse(String url, Context mContext) {
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
result = response;
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
mQueue.add(request);
return result;
}
}
The method in My activity where i am calling this class
private void callFunctionGetDist() {
ProgressDialog progressDialog;
progressDialog = ProgressDialog.show(recorddata.this, "", "Please Wait...", true);
JSONObject response = new VolleyWebService().getResponse(urlConfigClass.GET_DISTRICT, this);
try {
if(response.toString().contains("Status:Success,Details")){
arrDistName.clear();
arrDistCode.clear();
arrDistName.add("Select District Name");
arrDistCode.add("Select District Code");
JSONArray jsonArray = response.getJSONArray("Status:Success,Details");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jobJ = jsonArray.getJSONObject(i);
String scheName = jobJ.getString("post");
JSONObject jobJDist = new JSONObject(scheName);
String distname = jobJDist.getString("District");
String distcode = jobJDist.getString("DistrictCode");
arrDistName.add(distname);
arrDistCode.add(distcode);
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(recorddata.this,
R.layout.custom_textview_to_spinner, arrDistName);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
district.setAdapter(dataAdapter);
progressDialog.dismiss();
}else{
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Response is null or empty", Toast.LENGTH_LONG).show();
}
} catch (Exception volleyError) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
}
I tried creating the same class but i am not able to get the response to other activities. Although i am getting the correct response in the Volley jsonbject response, the response return null in other activities.
I want to have the result object return the response in my recorddata activity
This is what i have tried so far, no luck though!
public void postResponse (String url, Context mContext, final VolleyResponseListener listener) {
try {
String encodedUrl = url.replace(" ", "%20") + "";
if (encodedUrl.contains("("))
encodedUrl = encodedUrl.replace("(", "%28");
if (encodedUrl.contains(")"))
encodedUrl = encodedUrl.replace(")", "%29");
encodedUrl = encodedUrl.replace(" ", "%20");
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POst, encodedUrl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
listener.onSuccess(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.onError(error);
}
}) {
#Override
protected Map<String, String> getParams() {
return new HashMap<>();
}
};
mQueue.add(request);
} catch (Exception e) {
e.printStackTrace();
}
}
For the sake of achieving your goal, (without taking in to consideration architecture and coding principles), you can pass a callback:
public class VolleyWebService {
public interface VolleyResponseListener {
void onSuccess(JSONObject response);
void onError(VolleyError error);
}
public JSONObject result;
public JSONObject getResponse(String url, Context mContext, VolleyResponseListener listener) {
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
listener.onSuccess(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.onError(error);
}
});
mQueue.add(request);
return result;
}
}
To use it:
volleyWebService.getResponse("your url", context, new VolleyResponseListener() {
#Override
void onSuccess(JSONObject response) {
//do what you want on success
}
#Override
void onError(VolleyError error) {
//do what you want on error
}
});

AuthFailureError in Volley

I want to use from open street map API
when i send request to Reverse Geo coding Api with volley
This error is displayed
com.android.volley.authfailureerror
But this API don't need to any token
this is my Code:
String url = "https://nominatim.openstreetmap.org/reverse?format=json&lat="+lat+"&lon="+lng;
Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
try
{
JSONObject address = response.getJSONObject("address");
final String city = address.getString("town");
final String county = address.getString("county");
selectcity = true;
String temp = county.substring(county.indexOf(" "),county.length());
ed.putString("lat", lat+"");
ed.putString("lng", lng+"");
ed.putString("location", temp);
ed.apply();
progressDialog.dismiss();
RequestQueue mRequestQueue;
mRequestQueue =AppController.getInstance().getRequestQueue();
mRequestQueue.cancelAll("AppController");
locationManager.removeUpdates(LocationActivity.this);
}
catch (JSONException e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Erorr", Toast.LENGTH_LONG).show();
RequestQueue mRequestQueue;
mRequestQueue =AppController.getInstance().getRequestQueue();
mRequestQueue.cancelAll("AppController");
progressDialog.dismiss();
locationManager.removeUpdates(LocationActivity.this);
}
}
};
Response.ErrorListener errorListener = new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
RequestQueue mRequestQueue;
mRequestQueue =AppController.getInstance().getRequestQueue();
mRequestQueue.cancelAll("AppController");
progressDialog.dismiss();
locationManager.removeUpdates(LocationActivity.this);
}
};
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, listener, errorListener){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
headers.put("accept-language", "fa");
return headers;
}
};
request.setTag("AppController");
AppController.getInstance().addToRequestQueue(request);
In addition when I use from this URL in postman It works correctly
try this way
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
StringRequest stringRequest = new StringRequest(Request.Method.GET, Your_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("===","onErrorResponse "+error)
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
Log.d("===","AuthFailureError");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
#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
try {
} catch (Exception e) {
}
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
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.add(stringRequest);

How to use POST and GET method in Volley library?

I am using volley for login authentication,I passed values to the url by using JSON. Is it Correct Way? if not please tell me how to use POST and GET method in volley Library.i want to authentication to be done using volley library by passing string to the url
String loginurl = "http://www.souqalkhaleejia.com/webapis/login.php?email="+user+"&password="+pass;
Log.i("logurl", loginurl);
JsonObjectRequest loginreq = new JsonObjectRequest(Request.Method.POST, loginurl, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("Success")) {
String lomsg = response.getString("message");
String userid = response.getString("userid");
loginsession = new Session(getApplicationContext());
loginsession.createLoginSession(user, pass);
logineditor.putString("uid", userid);
logineditor.commit();
if (rememberme.isChecked()) {
logineditor.putBoolean("saveboolean", true);
logineditor.putString("uname", user);
logineditor.putString("pass", pass);
logineditor.commit();
} else {
logineditor.clear();
logineditor.commit();
}
Intent lognext = new Intent(MainActivity.this, Homescreen.class);
startActivity(lognext);
Toast.makeText(MainActivity.this, ""+lomsg,Toast.LENGTH_SHORT).show();
} else {
String errmsg = response.getString("message");
Toast.makeText(MainActivity.this,""+errmsg,Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "" + error,Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(loginreq);
}
You should pass the params like this
RequestQueue queue = Volley.newRequestQueue(context);
Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("userId", UserSingleton.getInstance(context).getUserId());
//jsonParams.put("userId", alert.getUser().getUserId());
// Request a string response from the provided URL.
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL , new JSONObject(jsonParams), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Response OK
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Error
}
});

Categories

Resources