I'm passing a key-value pair in String request using post request method I'm getting error 400.
The Error is:E/Volley: [1120] NetworkUtility.shouldRetryException: Unexpected response code 400 for http://11.1.1.86:9000/cef/investmentStrategies/android
RequestQueue MyRequestQueue = Volley.newRequestQueue(getContext());
url5 = "http://11.1.1.86:9000/cef/investmentStrategies/android";
StringRequest stringRequest5 = new StringRequest(Request.Method.POST, url5, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("No Error");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Error is here..");
}
}) {
#Nullable
#Override
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("Field",id);
return MyData;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
};
MyRequestQueue.add(stringRequest5);
}
Related
I am going to use volley to get data
RequestQueue queue = Volley.newRequestQueue(SummaryPhoneActivity.this);
String url = "https://covid19storageservice.table.core.windows.net/COVID19Survey?sv=2019-02-02&ss=bfqt&srt=sco&sp=rwdlacup&se=2020-06-30T18:04:08Z&st=2020-03-30T10:04:08Z&spr=https&sig=Ei3Kcr6xT5e7znK4ebwx6%2FVS09Ia5pbD1lnWRBh6bm4%3D";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, 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("error:", error.toString());
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
};
queue.add(stringRequest);
I can get error: com.android.volley.ClientError.
Above url is working on postman.
How can I use volley for above case. Thanks for your advance.
I am trying to send a post request to my server
my server read Headers of the request in String Format but getHeaders() in Volley return : Map< String, String >
Is there any way to send headers of request in string Format ?!
this is my Code Request :
Map<String, String> params = new HashMap<String, String>();
params.put("MY_FIRST_DATA_KEY", "MY_FIRST_DATA_VALUE");
params.put("MY_SECOND_DATA_KEY", "MY_SECOND_DATA_VALUE");
String url = "http://MY_URL.com";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "onResponse: " + response.toString() );
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: " + error.toString() );
error.printStackTrace();
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("MY_KEY","MY_VALUE");
/* HERE i need to return a String Value */
return headers;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(20000 , 3 , 3));
Volley.newRequestQueue(context).add(request);
try overriding getParams()
#Override
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put("MY_FIRST_DATA_KEY", "MY_FIRST_DATA_VALUE");
params.put("MY_SECOND_DATA_KEY", "MY_SECOND_DATA_VALUE");
return params;
}
You can add getParams() in the JsonObjectRequest()
#Override
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Parameter1", "value");
params.put("Parameter2", "value");
return params;
}
Hope it helps.
This is how I made a volley POST request adding headers and body
private void call_api(final String url){
if(!this.isFinishing() && getApplicationContext() != null){
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
resultsTextView.setVisibility(View.INVISIBLE);
loader.setVisibility(View.VISIBLE);
}
});
Log.e("APICALL", "\n token: " + url);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("APICALL", "\n response: " + response);
if(!FinalActivity.this.isFinishing()){
try {
JSONObject response_json_object = new JSONObject(response);
JSONArray linkupsSuggestionsArray = response_json_object.getJSONObject("data").getJSONArray("package");
final JSONObject k = linkupsSuggestionsArray.getJSONObject(0);
final String result = k.getJSONArray("action").getJSONObject(0).getString("url");
last_results = result;
last_results_type = k.getString("type");
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
loader.setVisibility(View.INVISIBLE);
resultsTextView.setText(result);
resultsTextView.setVisibility(View.VISIBLE);
}
});
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "An unexpected error occurred.", Toast.LENGTH_LONG).show();
finish();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("APICALL", "\n error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "Check your internet connection and try again", Toast.LENGTH_LONG).show();
finish();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("apiUser", "user");
headers.put("apiKey", "key");
headers.put("Accept", "application/json");
//headers.put("Contenttype", "application/json");
return headers;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<>();
map.put("location", "10.12 12.32");
return map;
}
};
stringRequest.setShouldCache(false);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}
When i call URL on postman, it returns expected result. I use PUT method using Volley, but it does not work.
StringRequest reg=new StringRequest(Request.Method.PUT, AppConfig.Registration, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("USER_REG",response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("USER_REG","-------------"+error);
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(name1,Name);
params.put(client_id1,CID);
params.put(email1,Email);
params.put(mobile1,Mobile);
params.put(password1,Password);
params.put(device_id1,"123456");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(reg);
Here's the postman output.
Currently you are sending the data from your Android using Volley as path parameters which should be sent as JSON like the following.
RequestQueue queue = Volley.newRequestQueue(this);
private void makeJsonObjReq() {
Map<String, String> postParam= new HashMap<String, String>();
postParam.put(name1,Name);
postParam.put(client_id1,CID);
postParam.put(email1,Email);
postParam.put(mobile1,Mobile);
postParam.put(password1,Password);
postParam.put(device_id1,"123456");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.PUT,
Const.YOUR_URL, new JSONObject(postParam),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
jsonObjReq.setTag(TAG);
queue.add(jsonObjReq);
You need to add the Content-Type as application/json in the header as well.
I am sending a volley request like this
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//submitForm();
JsonObjectRequest jsonobjectRequest = new JsonObjectRequest(Request.Method.POST, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//errorlabel.setText(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
errorlabel.setText("Invalid username / password");
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("email", "asd#asd.com");
params.put("password", "asd");
return params;
}
};
errorlabel.setText(jsonobjectRequest.toString());
requestQueue.add(jsonobjectRequest);
}
});
}
But I get an error message from the server saying invalid email/password.
I have set up the correct params. I tested it out on Postman and it works in there. Here is a screenshot.
Screenshot
I had same problem and i tried with String request, its working
StringRequest jsonObjRequest = 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) {
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> postParam = new HashMap<String, String>();
postParam.put("email", "asd#asd.com");
postParam.put("password", "asd");
return postParam;
}
};
requestQueue.add(jsonObjRequest);
i get this message com.android.volley.ParseError: org.json.JSONException: Value Email of type java.lang.String cannot be converted to JSONObjectError
i din't get any Response..
JsonObjectRequest jsr = new JsonObjectRequest(Request.Method.POST, REGISTER_URL, params, new Response.Listener() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString() + "Response");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error + "Error");
if( error instanceof ParseError) {
}
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
/**
* Set Time duration for Register Screen and and put JsonObjectRequest in volley RequestQueue Class.
* and take action according to RequestQueue Class.
*/
jsr.setRetryPolicy(new DefaultRetryPolicy(60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(Registers.this);
requestQueue.add(jsr);
break;
}
}
when i try to registerwith StringRequest i get this message in Backend..
WARN 10024 --- [nio-6060-exec-5] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON document: Unrecognized token 'phoneno': was expecting ('true', 'false' or 'null')
StringRequest sr = new StringRequest(Request.Method.POST, REGISTER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG,response.toString());
JSONObject params = new JSONObject();
try {
params.put("name", finalNAME);
params.put("email", finalMail);
params.put("city", finalCITY);
params.put("password", finalPASSWORD);
params.put("phoneno", finalMobile);
} catch (Exception ex) {
ex.printStackTrace();
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG,error.toString());
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("city", finalCITY);
params.put("email", finalMail);
params.put("name", finalNAME);
params.put("password", finalPASSWORD);
params.put("phoneno", finalMobile);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
*//* params.put("name", finalNAME1);
params.put("email", finalMail1);
params.put("city", finalCITY);
params.put("password", finalPASSWORD);
params.put("phoneno", finalMobile);
*//* params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
};
sr.setRetryPolicy(new DefaultRetryPolicy(60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(Registers.this);
requestQueue.add(sr);
break;
}}