Adding parameters on Restful API using JsonObjectRequest on Android Studio - android

I'm calling a restful api on my android project and I used Volley and JsonObjectRequest, I thought that the third parameter of the JsonObjectRequest which is jsonRequest are the api parameters so I created a json object for that which in the end I only got errors. So is it common to directly add the api parameters on the url? instead of passing it on a json object? what is the third parameter for, it would be really helpful if someone can give me an example. And my last question is how do you get the entire json response instead of using response.getString("title") for each key.
//api parameters directly added on the url
String URL = "https://www.myapi.com/?param=sample&param1=sample1";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String title = response.getString("Title");
Log.d("title", title);
} catch(Exception e){
Log.e("response error", e.toString());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.toString());
}
});

Below your Response.ErrorListener() you need to add these two overrides:
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.toString());
}) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("param", "sample");
params.put("param1", "sample1);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/x-www-form-urlencoded; charset=UTF-8");
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
return headers;
}
};

Related

Post Method using Volley not working

Hi i am using Volley for my login page. I need to pass data like this manner
{
userID : '-988682425884628921',
email :'aditya#vyas.com',
passwd : '123ss'
}
I am using POST Method to send data,I already check in DHC, The Api is working fine in DHC and I am getting JSON Response, But when i try with Volley i am not able to get response. and not even any error in my logcat.
JAVA code
RequestQueue mVolleyQueue = Volley.newRequestQueue(this);
CustomRequest req = new CustomRequest(Request.Method.POST,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.v("tag","login response " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v("tag","login error response " + error.getMessage());
}
}){
#Override
public Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("userID", "-988682425884628921");
params.put("email", "aditya#vyas.com");
params.put("passwd", "123ss");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
mVolleyQueue.add(req);
Error
05-28 09:20:14.696 2450-2468/com.android.msahakyan.expandablenavigationdrawer E/tag﹕ parseNetworkError is ! null
05-28 09:20:14.697 2450-2468/com.android.msahakyan.expandablenavigationdrawer E/tag﹕ parseNetworkError status code : 400
05-28 09:20:14.697 2450-2468/com.android.msahakyan.expandablenavigationdrawer E/tag﹕ parseNetworkError message : <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Header</h2>
<hr><p>HTTP Error 400. The request has an invalid header name.</p>
</BODY></HTML>
}
Solved your problem. Just used JsonArrayRequest and passed parameters in JsonObject form:
Map<String, String> params = new HashMap<String, String>();
params.put("userID", "userid");
params.put("email","email");
params.put("passwd", "password");
JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST, "url", new JSONObject(params),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
System.out.println("response -->> " + response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("change Pass response -->> " + error.toString());
}
});
request.setRetryPolicy(new
DefaultRetryPolicy(60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(activity).add(request);
No need of overriding getParams() or getHeaders().
Problem : 1
You were getting response code 500 because the server was accepting the params as JsonObject and we are trying to feed String.
Problem : 2
You were using JsonObjectRequet but the response from the server was in JsonArray so you need to use JsonArrayRequest to accept the response in JsonArray
Try and let me know this helps or not :)
I had a similar problem. I had overwritten the Content-Type in the getHeaders Method:
headers.put("Content-Type", "application/json; charset=UTF-8");
but Volley itself added a Content-Type parameter, so there were two of those parameters. Delete the line had solved my Problem.
You need to override protected Map<String, String> getParams() to pass parameters in POST.
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Login Response", response.toString());
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.getStackTrace());
VolleyLog.d("ErrorVolley", "Error: " + error.getStackTrace());
hidepDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("userID", "2"));
params.put("email","aa#a.kl");
params.put("passwd", "ddddd");
return params;
}
};
Beware of content-type header. Volley handles it differently from other headers and it's not shown in Map<> Headers. Instead of overriding getHeaders() method to set content-type, you should override getBodyContentType() like this:
#Override
public String getBodyContentType()
{
return "application/json; charset=utf-8";
}
i have same problem use this :
StringRequest stringRequest = new StringRequest(Request.Method.POST, 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> getParams() {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
headers.put("UN", UserName);
headers.put("PW", PassWord);
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
Just need to add headers.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); to parms
good luck.

Pass a JsonObject in Volley as POST parameter

I have an API endpoint which needs parameters to be sent as JsonObject in a POST request.
The response which I will get is not Json, but rather a small CSV string.
The Code is
stringRequest = new StringRequest(Request.Method.GET, "http://apitest.eezyrent.com/api/userauthentication/SignUp",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Toast.makeText(getApplication(), response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplication(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> jsonParams2 = new HashMap<String, String>();
jsonParams2.put("vcFName", firstname.getText().toString());
jsonParams2.put("vcLname", lastname.getText().toString());
jsonParams2.put("vcMobileNo", phone_no.getText().toString());
jsonParams2.put("vcGender", gender_short);
jsonParams2.put("vcEmailAddress", email.getText().toString());
jsonParams2.put("vcPassword", password.getText().toString());
jsonParams2.put("vcFBID", "");
jsonParams2.put("intLoginUserID", "");
jsonParams2.put("SignUpFrom", "Web");
jsonParams2.put("intloginid", "");
jsonParams2.put("AlreadyRegister", "");
return jsonParams2;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put( "charset", "utf-8");
return headers;
}
};
The above code is heavily inspired by using answers from this community, but this does not seem to solve the problem for me.
I get Volley Error 405.
E/Volley﹕ [112549] BasicNetwork.performRequest: Unexpected response code 405 for http://myurl
Infact If I used AsyncTask instead of Volley, With the same json as parameters and the same endpoint url. It works!! The AsyncTask code was found from this question. Java HttpClient changing content-type?
But I want to use Volley, What could be the solution to this?
Sample JSON Object
{"vcFName":"Ron","vcLname":"Weasley","vcMobileNo":"555888999","vcGender":"M","vcEmailAddress":"someone#somewhere.com","vcPassword":"123456","vcFBID":"","intLoginUserID":'',"SignUpFrom":"Web","intloginid":"","AlreadyRegister":""}
You need to use JsonObjectRequest class. Pass your params as json object in the 3rd parameter of the JsonObjectRequest class. Below is a small snippet:
Map<String, String> jsonParams2 = new HashMap<String, String>();
jsonParams2.put("vcFName", firstname.getText().toString());
jsonParams2.put("vcLname", lastname.getText().toString());
jsonParams2.put("vcMobileNo", phone_no.getText().toString());
jsonParams2.put("vcGender", gender_short);
jsonParams2.put("vcEmailAddress", email.getText().toString());
jsonParams2.put("vcPassword", password.getText().toString());
jsonParams2.put("vcFBID", "");
jsonParams2.put("intLoginUserID", "");
jsonParams2.put("SignUpFrom", "Web");
jsonParams2.put("intloginid", "");
jsonParams2.put("AlreadyRegister", "");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
YourUrl, new JsonObject(jsonParams2),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put( "charset", "utf-8");
return headers;
}
};
Step 1: Make model class parsable/Serializable.
Step 2: Override toString() in model class.
Step 3:
Map<String,JSONObject> params = new HashMap<>();
JSONObject object = null;
try{
object = new JSONObject(classObject.toString());
}catch (Exception e){
}
params.put("key", object);
JSONObject objectParams = new JSONObject(params);
Step 4: Send objectParams with volley JSONObject request.
Done!!!

Volley: unable to set break point for onResponse method

I am using Volley Library to make network calls and I am using it for the first time. I am trying to set a break point in onResponse method but the break point is getting toggled on JsonObjectRequest. Following is my code
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, urlL1, "", new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(CVLenderApp.TAG, response.toString());
// I would like to set the break point at this line
Toast.makeText(SignInActivity.this, "Success", 3000).show();
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(CVLenderApp.TAG, "Error: " + error.getMessage());
pDialog.hide();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("userName", "name");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
};
// Adding request to request queue
CVLenderApp.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
I hope I'm doing a small mistake, but I'm unable to figure that out.
Thank you,
Anudeep Reddy.
As I commented, for POST request's parameters, override getBody instead of getParams
Moreover, if your project uses Google's official Volley, then try the following sample code:
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("userName", "name");
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// do something...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something...
}
});
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
Hope this helps!

Post JsonObject with Volley

I'm trying to send a Post request with volley without success.
The lib is working correctly, and I manage to sent some string requests, but the Post with a JsonObject doesn't work.
String urlJsonReq = "https://api.parse.com/1/classes/GameScore";
String tag_json_obj = "tag_json";
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.POST,
urlJsonReq,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("MyApp", response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("MyApp", "Error: " + error.getMessage());
// hide the progress dialog
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("value1", "testValue1");
params.put("value2", "testValue2");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("X-Parse-REST-API-Key", "xxxxxxxxxxxx");
headers.put("X-Parse-Application-Id", "xxxxxxxxxxx");
return headers;
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
I keep getting an error. I read somewhere, but without any details that the volley cannot sent JsonObjects, only receive then. That if you want to solve that problem you should implement an custom class, but I really don't know if I'm just making an stupid mistake here (it is possible).
Do you guys know something about that?
Thank you for your time.
You can send the JSONObject without overiding the getParams or getBodyContentType. Something like this for example
JSONObject object = new JSONObject();
JsonObjectRequest jr = new JsonObjectRequest(Request.Method.POST, url, object, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Obviously you can Override the headers if you need to.

Passing Parameters into Android Volley POST Request, return JSON

I am attempting a Volley POST request that passes in the parameter friends_phone_number_csv that should then return a JSON object. However in using the request below it simply notes:
E/Volley﹕ [4230] BasicNetwork.performRequest: Unexpected response code 500 for http://(ip-address):3000/getActivatedFriends.json
In testing this request in chromes POSTMAN I know the webservice is correct and should return a JSON object.
How can I make this work?
The POST request in app:
JsonObjectRequest getUserActiveFriends = new JsonObjectRequest(Request.Method.POST, "http://" + Global.getFeastOnline() + "/getActivatedFriends.json",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
resultObject = response.getJSONObject("friends_match");
Toast.makeText(getApplicationContext(), resultObject.toString(), Toast.LENGTH_LONG).show();
// PARSE THE REST
//Log.v("USER ID", "The user id is " + userId);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("friends_phone_number_csv", contactsNumbers);
return params;
}
};
requestQueue.add(getUserActiveFriends);
You should add this code, when you post request and return json data, you should add content type "application/json; charset=utf-8" to http header.
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}

Categories

Resources