Using volley to make web service call - android

I have a web api setup and one of the endpoints in the API takes a JSON object (which in the API gets resolved to a .NET object).
Using Postman I can successfully call the post endpoint, here is the URL
https://example.com/api/helprequests
And here is the JSON which I include in the Postman request
{"Title":"Test Title", "Message":"Test Message"}
Everything works well in Postman, but I am trying to call this API from an Android app using Volley.
Here is the relevant code
String webAddress = "http://example.com/api/helprequests/";
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, webAddress,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("RESPONSE", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("RESPONSE", "That didn't work!");
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
Map<String, String> params = new HashMap<String, String>();
params.put("Title","Test title");
params.put("Message", "Test message");
} catch (Exception ex) {
VolleyLog.wtf("Unsupported Encoding");
return null;
}
return null;
}
};
queue.add(stringRequest);
When I run this I get the following error:
E/Volley: [50225] BasicNetwork.performRequest: Unexpected response code 500 for https://example.com/api/helprequests
How do I add post data to a Volley request?

Instead of using the StringRequest do use JsonObjectRequest.
String webAddress = "http://example.com/api/helprequests/";
RequestQueue queue = Volley.newRequestQueue(this);
JSONObject object = new JSONObject();
try {
object.put("Title", "my title");
object.put("Message", "my message");
} 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!");
}
});
queue.add(request);

String webAddress = "http://example.com/api/helprequests/";
RequestQueue queue = Volley.newRequestQueue(this);
JSONObject jsonObject= new JSONObject();
try {
jsonObject.put("Title", "my title");
jsonObject.put("Message", "my message");
} catch (JSONException e) {
}
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequestWithHeader jsonObjReq = new JsonObjectRequestWithHeader(Request.Method.POST,
webAddress , jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.v("Response0", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Response", "Error: " + error.getMessage());
pd.dismiss();
}
});
int socketTimeout = 50000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjReq.setRetryPolicy(policy);
queue.add(jsonObjReq);
return null;
}

Related

Unable to call POST method using Volley

Code as below:
public void loginPost(String url, String emailAddress, String password){
Map<String, String> params = new HashMap();
params.put("email", emailAddress);
params.put("password", password);
JSONObject parameters = new JSONObject(params);
String LOGIN_REQUEST_TAG = "LOGIN_REQUEST_TAG";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, parameters, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Login Response:", response.toString());
JSONObject responseOject = response;
if(responseOject.has("data")){
try {
Log.d("Data Response", responseOject.getString("data"));
} catch (JSONException e) {
e.printStackTrace();
}
}else if(responseOject.has("error")){
try {
errorMessage = responseOject.getString("error");
new AlertDialog.Builder(MainActivity.this)
.setTitle("Error")
.setMessage(errorMessage)
.setNegativeButton("OK", null)
.show();
} catch (JSONException e) {
e.printStackTrace();
}
}else{
//Server error. Come back again later
Log.d("Server error", "Server Error");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error at login: ", error.getMessage());
}
});
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest,LOGIN_REQUEST_TAG);
}
All the parameters and URL are correct as I have checked it during debug. And everything works fine in Postman as well. However, the code above just wont go into onResponse method and I am not receiving any error. But it is giving a warning that "responseOject" is redundant. Am I doing it wrongly? Quite new to Android development.
Error:
BasicNetwork.performRequest: Unexpected response code 401
It is a POST API and I am using Request.Method.Post, why am I receiving that error?
Before using the API test it in Postman. You will get a clear view of what is happening.
The error code 401 means you parameters are wrong. OR you are unauthorized to access that API.
Try this code for this type of call.
private void callNetwork(final String email, final String password) {
String json_object_request = "jsonObjectRequest";
//Creating a string request
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response != null) {
parseData(response);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
//Adding parameters to request
params.put("email", email);
params.put("password", password);
//returning parameter
return params;
}
};
//Adding the string request to the queue
AppController.getInstance().addToRequestQueue(stringRequest, json_object_request);
}

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

Volley What Request Type to use for the format

I'm New to android Volley. I accessing a API server and its response is JSON.
The response JSON is like this\
{
status:true,
data : [{
id:1,
name:'name 1',
},
{
id:2,
name:'name 2 ',
}]
}
I tried using JsonObjectRequest & JsonArrayRequest in Volley. Both throws error. What is the Right request type to use and How to parse it?
You will need to use a JsonObjectRequest for this, if it is a post request use the following
try{
JSONObject jsonBody = new JSONObject("add json body to post");
RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(LookUp.url, jsonBody,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// pDialog.cancel();
try{
if(response.getString("status").equals("true")){
JSONArray jsonArray=response.getJSONArray("data");
for(int i=0;i<jsonArray.length();i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name=jsonObject.getString("name");
}
}
}
catch (JSONException error){
Log.e("TAGJE", error.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAGE", error.getMessage(), error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/json");
return params;
}
};
mQueue.add(jsonObjectRequest);
}
catch (JSONException ex){
ex.printStackTrace();
}
and for a get request follow this
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try{
if(response.getString("status").equals("true")){
JSONArray jsonArray=response.getJSONArray("data");
for(int i=0;i<jsonArray.length();i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name=jsonObject.getString("name");
}
}
}
catch (JSONException error){
Log.e("TAGJE", error.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});

Volley sends null parameters to server

I'm trying to send JSON parameter but server is receiving them as nulls values,
i tried to request it from Postman and it works perfect, i don't know what the problem is with volley i followed the instructions here but it didn't make sense
here is my code
String url = "http://10.10.10.166:8080/SystemManagement/api/Profile/Login";
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("user_id","Test user name");
jsonObject.put("user_password","test password");
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(jsonObject.toString());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( Request.Method.POST, url, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(Login.this, response.toString(),Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.toString());
}
});
//add request to queue
queue.add(jsonObjectRequest);
I faced same problem, solved by overriding the getParams() method
Here is my login request using Volley.
private void loginRequeset() {
showpDialog();
StringRequest jsonObjReq = new StringRequest(Request.Method.POST, Constants.LOGIN_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(Login.this, response.toString(),Toast.LENGTH_SHORT).show();
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> signup_param = new HashMap<String, String>();
signup_param.put(Constants.USERNAME, _emailText.getText().toString().trim());
signup_param.put(Constants.PASSWORD, _passwordText.getText().toString().trim());
return signup_param;
}
};
// Adding request to request queue
queue.getInstance().addToRequestQueue(jsonObjReq);
}

How to send Json POST request using Volley in android in the Given Tutorial?

Hi I am a beginner in Android , I am learning to make Api Calls. I got a tutorial of Volley which uses GET to Receive response. Now I want to Send Post request Using Volley. I don't know how to do that, what would be the code for POST in the given Tutorial. Please guide me to send Post Request.The link to the tutorial that I am learning is http://www.truiton.com/2015/02/android-volley-example/
you have to used below code to send request
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// 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) {
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
try {
/** json object parameter**/
JSONObject jsonObject = new JSONObject();
jsonObject.put("hello", "hello");
Log.e("jsonObject params", jsonObject.toString() + "");
/**URL */
String url ="http://google.com"
progress.setVisibility(View.VISIBLE);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
progress.setVisibility(View.GONE);
Log.e(TAG, "Response " + jsonObject.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
progress.setVisibility(View.GONE);
Log.e(TAG, volleyError);
Util.showToast(activity, "Please try again");
}
});
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
progress.setVisibility(View.GONE);
Log.e(TAG, e);
}
catch (Exception e) {
progress.setVisibility(View.GONE);
Log.e(TAG, e);
}
}
}
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(jsonObjectRequest);
You can follow this :http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
StringRequest request = new StringRequest(Method.POST,
"post url",
new ResponseListener() {
#Override
public void onResponse(String response) {
Log.d("response", response);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("response","error");
}
}) {
// post params
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("param", "param");
return params;
}
};
//2.Use your custom volley manager send request or like this
Volley.newRequestQueue(mCtx).add(request);

Categories

Resources