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);
}
Related
I am trying to send json data to a url in the format below.
{
“amount”:500,
“merchant_id”:”104”,
“narrative”:”John”,
“reference”:”Steven”
}
To send data to the url, one needs an authorization key as the header, I have already figured out how to set the authorization key as the header in Params, as shown below
#Override
public Map<String,String >getHeaders()throws AuthFailureError{
Map<String,String >params=new HashMap<String,String>();
params.put(“Content-Type”, “text/jsom;);
params.put(“AuthKey”, Auth);
return params;
but I do not know how to send the data in the particular format shown in the first instance to the url using params with volley. Please help, I am quite new to using Volley library .
This is the rest of code I am currently using it however does not return any response except for an invalid json error. Meaning the format sent is not corresponding to the one desired.
StringRequest stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(Main9Activity.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Main9Activity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() {
HashMap<String, String> params = new HashMap<String, String>();
params.put("amount","500");
params.put("merchant_id", "104");
params.put("narrative","John");
params.put("reference", "Steven");
return params;
}
#Override public Map<String,String>getHeaders()throws AuthFailureError{
Map<String,String>headers=new HashMap<>();
params.put("Content-Type","text/json");
params.put("Authorization",Auth);
return params;
}
};
RequestQueue requestQueue=Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
You can refer below code snipet to post data with custom header in volley.
JSONObject jsonobject = new JSONObject();
jsonobject.put("amount", "500");
jsonobject.put("merchant_id", "104");
jsonobject.put("narrative", "John");
jsonobject.put("reference", "Steven");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.POST,url, jsonobject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
Toast.makeText(Main9Activity.this, response.toString(), Toast.LENGTH_SHORT).show();
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(Main9Activity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
hideProgressDialog();
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String >headers=new HashMap<String,String>();
headers.put(“Content-Type”, “application/json“);
headers.put(“AuthKey”, Auth);
return headers;
}
You can send as below:
The data you want to send:
Hashmap<String, Object> data = new HashMap<>();
data.put("amount", "500");
data.put("merchant_id", "104");
data.put("narrative", "John");
data.put("reference", "Steven");
RequestQueue request = Volley.newRequestQueue(context);
JsonObjectRequest jsonobj = new JsonObjectRequest(Request.Method.POST, "your url",new JSONObject(data),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
){
};
request.add(jsonobj);
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);
}
I am using android volley library to post data to back-end service. But I can't send any parameter with my request. I have done each and everything mentioned here . But none works for me. The post method that I am using is:
public static void post()
{
// Tag used to cancel the request
String tag_json_obj = "json_obj_req";
String url = "http://myUrl";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
return headers;
}
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("key", "value");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
Always the response is "parameter missing".
How could i resolve this issue?
If you're using JSONObjectRequest, you can try this.
String url = "http://myurl";
Map<String, String> params = new HashMap<String, String>();
params.put("key", value);
RequestQueue queue = Volley.newRequestQueue(getActivity());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
url, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
try {
success = jsonObject.getInt("success");
message = jsonObject.getString("message");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Activity activity = getActivity();
if (volleyError instanceof NoConnectionError) {
String errormsg = "Check your internet connection";
Toast.makeText(activity, errormsg, Toast.LENGTH_LONG).show();
}
}
});
queue.add(jsonObjectRequest);
The codes are more likely the same as yours. Check on the lines where I put the data to be posted. I'm very sure this would work!
The problem is you are approaching the request as though you were making a stringRequest. The link you reference is talking specifically about making a stringRequest.
jsonObjectRequest actually lets you put the json object into the constructor itself, instead of using the override method getParams() like so:
String url = "some_url";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put(Constants.LOGIN_EMAIL_ID, email);
jsonObject.put(Constants.LOGIN_PASSWORD, password);
}catch(JSONException e){
Log.d("JSON error", e.getMessage(), e);
}
JsonObjectRequest jsObjRequest = new JsonObjectRequest(url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("RESPONSE", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(error.getMessage()!=null){
Log.d("RESPONSE", error.getMessage());
}
}
});
VolleySingleton.getInstance(activity).getRequestQueue().add(jsObjRequest);
I have to make a json post request with the following parameters.
{"method":"login","data":{"username":"korea","password":"123456"}}
I use volley to make post request and follwoing is my code to do post request.
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, loginURL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(mContext,response.toString(),Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = new HashMap<String,String>();
map.put("method","login");
map.put("username","korea");
map.put("password","123456");
return map;
}
};
requestQueue.add(jsonObjectRequest);
requestQueue.start();
Im getting error response from server. How to get proper response from server?
Change Request.Method.GET to Request.Method.POST. Then pass a JSONObject as the third parameter where you currently have null;
For example:
JSONObject data = new JSONObject();
data.put("username","korea");
data.put("password","123456");
JSONObject jsonObject = new JSONObject();
jsonObject.put("method","login");
jsonObject.put("data",data);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, loginURL, jsonObject, responseListener, errorListener);
I use volley to make post request and follwoing is my code to do post request
That is not a POST request, AFAICT. You are using Request.Method.GET.
Use following method to post the data to server
public void postDataVolley(Context context,String url,JSONObject sendObj){
try {
RequestQueue queue = Volley.newRequestQueue(context);
JsonObjectRequest jsonObj = new JsonObjectRequest(url,sendObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Volley", "Volley JSON post" + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Volley", "Volley JSON post" + "That didn't work!");
}
});
queue.add(jsonObj);
}catch(Exception e){
}
}
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);