How to Post raw data using volley - java

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();
}

Related

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

How to get Volley POST response body?

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");

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 send this type of data in post request in volley?

This wants to send JsonObject in key Json. So please tell how to send it using volley.
json={"product":"magie"}
How to send this data in Volley, I have add the asyncTask code below for hit api with that type of data.
enter code here
protected void onPreExecute() {
if (progress)
GlobalAlerts.showProgressDialog(context);
}
#Override
protected String doInBackground(String... params) {
String resp = null;
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("product","magie");
} catch (JSONException e) {
e.printStackTrace();
}
String data = "json=" + jsonObject.toString();
String url ="http://anc.php";
resp = new JsonCall().executeHttpPostRequest(url, data);
return resp;
}
protected void onPostExecute(String resp) {
if (progress)
GlobalAlerts.hideProgressDialog();
if (resp != null) {
callback.onTaskComplete(resp);
} else {
GlobalAlerts.singleAlert((Activity) context, context.getString(R.string.warning), "Error", false);
}
}
Answer for that is like put data in jsonObject and then pass jsonObject in hashmap with key json.
enter code here
String url = "http://anc.php";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("product", "magie");
} catch (JSONException e) {
e.printStackTrace();
}
final HashMap<String,String> hashMap2 = new HashMap<>();
hashMap2.put("json",jsonObject.toString());
StringRequest strReq = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("order_list", response);
GlobalAlerts.hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", "Error: " + error.getMessage());
GlobalAlerts.hideProgressDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
/*Map<String,String> params = new HashMap<>();
params.put("employee_id"," 1");*/
return hashMap2;
}
};
Application.getInstance().addToRequestQueue(strReq, "order_list");

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