Volley - BasicNetwork.performRequest: Unexpected response code 400 POST - java

Postman Header
[{"key":"Content-Type","name":"Content-Type","type":"text","value":"application/json"},{"key":"token","type":"text","value":"ffBJpLW55i"}]
even if i put token value instead of the token string it wont work
headers.put("Content-Type", "application/json");
headers.put("token", "ffBJpLW55i");
2019-03-15 21:51:15.384 20577-20620/com.sleepyhitman.ab4_internship_2019try2 E/Volley: [816] BasicNetwork.performRequest: Unexpected response code 400 for https://tralalala.com/api-spot-get-all
private void loadRecyclerViewData(final String token){
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest listRequest = new StringRequest(Request.Method.POST,URL_DATA+"api-spot-get-all",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("result");
for (int i =0; i<array.length(); i++) {
JSONObject o = array.getJSONObject(i);
ListItem list = new ListItem(
o.getString("id"),
o.getString("name"),
o.getString("country"),
o.getString("whenToGo"),
o.getBoolean("isFavorite")
);
listItems.add(list);
}
ListItemAdapter listItemAdapter = new ListItemAdapter(getApplicationContext(), listItems);
recyclerView.setAdapter(listItemAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
//
}
},
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("token", token);
return headers;
}
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("country", "");
params.put("windProbability", "");
return params;
}
};
requestQueue.add(listRequest);
}

This part is the error part of your volley request,
URL_DATA+"api-spot-get-all"
There should be a URL in string format as you are using StringRequest.

Related

Error 400 in android volley while using POST request method

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

How to fix "Volley: [15771] BasicNetwork.performRequest: Unexpected response code 404 in android?

The API is developed in Wordpress with POST method. API is working fine in POSTMAN and iOS(swift). I am getting response in POSTMAN and my colleague iOS developer also getting response.
But in Android I am getting 404 error in Android Studio.
I am trying to resolve with different Volley request like StringRequest, JSONObjectRequest and HttpURLConnection with AsyncTask. But getting only 404 error. Any one tell me what is the exact issue?
Below is my code.
private void RegisterUser(){
final ProgressDialog progressDialog = new ProgressDialog(RegistrationActivity.this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Please wait...");
progressDialog.show();
StringRequest postrequest = new StringRequest(Request.Method.POST, Urls.REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
progressDialog.dismiss();
Log.e("res","==> "+response);
}
catch (Exception e){e.printStackTrace();}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {progressDialog.dismiss();error.getLocalizedMessage();}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("username", "khushbu");
params.put("email", "kh#test.com");
params.put("user_pass", "test#123");
params.put("display_name", "khushbu");
params.put("company_name", "");
params.put("nature_of_business", "");
params.put("country", "");
params.put("nonce", "12e099a946");
params.put("notify", "both");
params.put("insecure", "cool");
Log.e("params","==> " + params);
return params;
}
};
FlawlessApplication.getInstance().addToRequestQueue(postrequest);
}
I also tried with adding headers but can't get any solution.
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
params.put("cache-control", "no-cache");
return params;
}
Thank you in advance.
final ProgressDialog progressDialog;
progressDialog = ProgressDialog.show(mContext, "", "Loading..");
progressDialog.setCancelable(false);
progressDialog.show();
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
HashMap<String, String> params = new HashMap<>();
params.put("username", "khushbu");
params.put("email", "kh#test.com");
params.put("user_pass", "test#123");
params.put("display_name", "khushbu");
params.put("company_name", "");
params.put("nature_of_business", "");
params.put("country", "");
params.put("nonce", "12e099a946");
params.put("notify", "both");
params.put("insecure", "cool");
Log.e("params","==> " + params);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST,
Urls.REGISTER,
new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
progressDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
try {
Log.e("res","==> "+response);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Do something when error occurred
try {
progressDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headerParams = new HashMap<>();
//add header params if having
headerParams.put("KEY", "value");
return headerParams;
}
};
// Add JsonObjectRequest to the RequestQueue
requestQueue.add(jsonObjectRequest);
In my case.
I was using the http in my API so after changing to https it worked for me. and in postman no matter it http or https it works the same.

how to POST raw type JSON Data in Body?

I'm sending a post request to server using Volley request and i have some raw Type JSON data that has to be sent. Here I have no idea how to send the
4th object students which is type of Array.
JSON data to be posted is
{
"course_id":1,
"batch_id":1,
"subject_id":1,
"students":[{"student_id":6,"present":0},{"student_id":17,"present":0}]
}
My code
private void fetchDataAndMarkAttendence() {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
status = jsonObject.getString("status");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> map = new HashMap<String, String>();
SharedPreferences prefs = getApplicationContext().getSharedPreferences(MY_PREFS_NAME, Activity.MODE_PRIVATE);
token = prefs.getString("token","");
map.put("Authorization", "Token "+token);
return map;
}
}
}
So, any help regarding how can i post the JSON data mentioned above will be helpfull.
This is called JSONArray.
try {
JSONArray jsonArray = jsonObject.getJSONArray();
for (int i = 0; i < jsonArray.length(); i++) {
int student_id = jsonObject.getInt("student_id");
int present = jsonObject.getInt("present");
}
} catch (JSONException e) {
e.printStackTrace();
}
EDIT
as mention, you want to post the json. So create the json suing below code and post mainJsonObject.toString(); as parameter.
try {
JSONObject mainJsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
//if more than one then wrap inside loop
JSONObject jsonObject = new JSONObject();
jsonObject.put("student_id", value);
jsonObject.put("present", value);
jsonArray.put(jsonObject);
//end loop
mainJsonObject.put("course_id", value);
mainJsonObject.put("batch_id", value);
mainJsonObject.put("subject_id", value);
mainJsonObject.put("students", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
hope it helps.
Replace your StringRequest with JsonObjectRequest
JSONObject postparams = new JSONObject();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, postparams,
new Response.Listener() {
#Override
public void onResponse(JSONObject response) {
//Success Callback
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Failure Callback
}
});
can you try this? This probably will fix your problem.
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
status = jsonObject.getString("status");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
public byte[] getBody() throws AuthFailureError {
String yourJSON = yourJsonObj.toString() ;
return yourJSON.getBytes();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> map = new HashMap<String, String>();
SharedPreferences prefs = getApplicationContext().getSharedPreferences(MY_PREFS_NAME, Activity.MODE_PRIVATE);
token = prefs.getString("token","");
map.put("Authorization", "Token "+token);
return map;
}
};

Send Header And Data(Body) as String in Volley

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

POST json array to Mysql database using JsonArrayRequest using volley in android?

This is my code for JsonArrayRequest I think either it is incomplete or incorrect. The problem is nothing getting added into the database and I am not getting any errors. I am new to programming so I have no idea as to where I might be going wrong.
private void insertToDb() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, INVEST_URL,
itemSelectedJson, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Toast.makeText(AddInvEst.this, "The echoed response is "+response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String, String>();
headers.put("Content-Type","application/json");
headers.put("Accept", "application/json");
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
This is code for creating a jsonArray
private void selectedItems() {
billType = (invEstSwitch.isChecked() ? textViewEstimate : textViewInvoice)
.getText().toString();
itemselected.put("custInfo", custSelected.toString());
itemselected.put("invoiceNo", textViewInvNo.getText().toString());
itemselected.put("barcode", barCode.getText().toString());
itemselected.put("desc", itemDesc.getText().toString());
itemselected.put("weight", weightLine.getText().toString());
itemselected.put("rate", rateAmount.getText().toString());
itemselected.put("makingAmt", makingAmount.getText().toString());
itemselected.put("net_rate", netRate.getText().toString());
itemselected.put("itemTotal", itemtotal.getText().toString());
itemselected.put("vat", textViewVat.getText().toString());
itemselected.put("sum_total", textViewSum.getText().toString());
itemselected.put("bill_type", billType);
itemselected.put("date", textViewCurrentDate.getText().toString());
//Add the map to the Array
itemSelectedJson.put(itemselected);
index++;
}
And this is my php code.
<?php
require "init.php";
$json = file_get_contents('php://input');
//$data = json_decode($json,true);
// remove the ,true so the data is not all converted to arrays
$data = json_decode($json);
// Now process the array of objects
foreach ( $data as $inv ) {
$custInfo = $inv->custInfo;
$rate = $inv->rate;
$weight= $inv->weight;
$desc= $inv->desc;
$makingAmt= $inv->makingAmt;
$vat= $inv->vat;
$itemTotal= $inv->itemTotal;
$sum_total= $inv->sum_total;
$barcode= $inv->barcode;
$net_rate= $inv->net_rate;
$date= $inv->date;
$invoiceNo= $inv->invoiceNo;
$bill_type= $inv->bill_type;
$sql = "INSERT INTO selected_items
(custInfo, invoiceNo, barcode, desc,
weight, rate, makingAmt,net_rate,
itemTotal,vat,sum_total,bill_type,date)
VALUES
('$custInfo','$invoiceNo','$barcode','$desc',
'$weight','$rate','$makingAmt','$net_rate',
'$itemTotal','$vat','$sum_total','$bill_type','$date')";
$res = mysql_query($sql,$con);
if(!$res){
$result = new stdClass();
$result->status = false;
$result->msg = mysql_error();
echo json_encode($result);
exit;
}
}
?>
You missed to add a method getParams() inside the post request, it should have this structure
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) {
errorHandler(error);
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
//Adding parameters to request
params.put("KEY1", key1);
params.put("KEY2", key2);
//returning parameter
return params;
}
};
//Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}

Categories