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

E/Volley: [1888] BasicNetwork.performRequest: Unexpected response code 400 for https://pastebin.com/raw/2WMVsLei
Problem only Pastbin. I will try another https api but can't face any issue. Issue only occurs with pastebin api.
public void logIn() {
String URL="";
try {
JSONObject old = new JSONObject(Constantse.decrypt(PreferenceUtils.getAllData(con)));
String updateUrl = old.getString("DefUpdateURL");
URL = updateUrl;
}catch (Exception e){
System.out.println(e);
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject old = new JSONObject(Constantse.decrypt(PreferenceUtils.getAllData(con)));
JSONObject news = new JSONObject(Constantse.decrypt(response));
System.out.println(Constantse.decrypt(response));
if(Integer.parseInt(news.getString("UpdateVersion")) > Integer.parseInt(old.getString("UpdateVersion"))){
PreferenceUtils.setCredientials(con,news.getJSONArray("Servers").toString());
PreferenceUtils.setPayload(con,news.getJSONArray("payload").toString());
PreferenceUtils.setAllData(con,response);
editor.putInt("current_server", 0).apply();
editor.putInt("current_payload", 0).apply();
Toast.makeText(getActivity(),"Update Success",Toast.LENGTH_SHORT).show();
getActivity().finish();
startActivity(getActivity().getIntent());
}else{
System.out.println("Don't Update");
Toast.makeText(getActivity(),"Already Updated",Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
System.out.println(e);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
logIn2(); // this is additional api for server & payload
Toast.makeText(getActivity(),"Use Next Server",Toast.LENGTH_SHORT).show();
System.out.println(error);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
stringRequest.setShouldCache(false);// for cash clear
Volley.newRequestQueue(con).add(stringRequest);
Volley.newRequestQueue(con).getCache().clear();// for cash clear
}

Related

How to get String response from post request volley

I am trying to get a string response from post request. Here, I am sending a post request. where I am sending this data. I have a Model of BillReceipt. Which I pass on the request body.
public void UserTransactionReceiptReport(TransactionTypeListener<String> listener, BillReceipt billReceiptReport){
final UserSettings userSettings = getMUserSettings();
final StringBuilder url = new StringBuilder(AppConfigsManager.getTouchServerUrl());
url.append("/api/User/UserData");
JSONObject params = new JSONObject();
try{
params.put("iB_CUST_ID",billReceiptReport.getiB_CUST_ID());
params.put("transactioN_DATE",billReceiptReport.getTransactioN_DATE());
params.put("transactioN_DATE_NM",billReceiptReport.getTransactioN_DATE_NM());
}catch (Exception e){
e.printStackTrace();
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url.toString(), params
, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Gson mapper = new GsonBuilder().create();
try{
Type type = new TypeToken<APIResponse<String>>() {
}.getType();
APIResponse<String> responseObject = mapper.fromJson(response.toString(), type);
if(responseObject.Status == APIStatus.OK){
listener.didFetch(responseObject.Result, responseObject.Message);
}else {
listener.didError(responseObject.Message);
}
}catch (Exception e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.didError(error.getMessage());
}
})
{
#Override
public Map<String, String> getHeaders() {
return getAuthorizationTokenHashMap(getMUserSettings());
}
};
addVolleyRequest(request);
}
and I call this api from recycler download button.Here , I globally declared the manager where i write the api code. and also declare a the model name.
holder.downloadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
manager.UserTransactionReceiptReport(listener,billReceiptReport);
}
});
}
private final TransactionTypeListener<String> listener = new TransactionTypeListener<String>() {
#Override
public void didFetch(String response, String message) {
str = response;
}
#Override
public void didError(String message) {
}
};
any one help me to solve the problem i am facing.
Try this code
<code>
JSONObject jsonObject = new JSONObject(response);
System.out.println("jsonWallet----" + jsonObject);
int status_ = jsonObject.getInt("status");
if(status_ == 1){
String incomeWalletBal = jsonObject.getString("income_wallet");
String refundWalletBal = jsonObject.getString("refund_wallet");
}else {
}
</code>

How to send params to json array request in android volley

I have a students table.
I am trying to send request to and REST APP using the HTTPS and JSON Array from the Android studio to My web-based application.
My request works fine.
The problem I am getting is how to send params in the request.
public void SyncRoutsAfterExport(){
//Send request to server to get routes
//Request que
RequestQueue mQueue = Volley.newRequestQueue(UserProfile.this);
//Json perse function
String url = "xxxxxxxxxxxxxxxxxx";
Map<String, String> params = new HashMap<String, String>();
params.put("name", "mark");
params.put("nam", "someOtherVal");
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++){
try {
JSONObject jresponse = response.getJSONObject(i);
String name= jresponse.getInt("name");
String age= jresponse.getString("age");
AddDatatotable(name,age);
if(i == response.length() -1){
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
so In the above code, I want to send couple of params name and age. How to send the above request with params.
I think you can try StringRequest and overload getParams Method
RequestQueue mQueue = Volley.newRequestQueue(UserProfile.this);
//Json perse function
String url = "xxxxxxxxxxxxxxxxxx";
Map<String, String> params = new HashMap<String, String>();
params.put("name", "mark");
params.put("nam", "someOtherVal");
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String requestResponse) {
JSONArray response
try {
array=new JSONArray(requestResponse);
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < response.length(); i++){
try {
JSONObject jresponse = response.getJSONObject(i);
String name= jresponse.getInt("name");
String age= jresponse.getString("age");
AddDatatotable(name,age);
if(i == response.length() -1){
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return params;
}
};
mQueue.add(request);

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

Sending a POST request with Volley to PHP Script

Im trying to send POST request with Volley from Android App to PHP script hosted on my server. When i get the response code i get Code 200 Successfull but $_POST in PHP script is empty.
My android Request code:
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = getResources().getString(R.string.web_login);
JSONObject jsonBody = new JSONObject();
jsonBody.put("hello", "world");
jsonBody.put("username", username);
final String mRequestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("LOG_VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG_VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "text/plain; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
try {
responseString = new String(response.data, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
This code works fine, but when i get the response header it contains the next PHP Error:
Undefined index: username
Here is my php Script:
<?php
//Get post data from Android App
$name = $_POST['username'];
if (isset($name)){
$data = "OK";
header('Content-Type: text/plain');
echo $data;
}
?>
What am I doing wrong?
POST parameters should be sent from getParams().
Try:
try {
final HashMap<String, String> params = new HashMap<>();
params.put("username", username);
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = getResources().getString(R.string.web_login);
JSONObject jsonBody = new JSONObject();
jsonBody.put("hello", "world");
jsonBody.put("username", username);
final String mRequestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("LOG_VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG_VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "text/plain; charset=utf-8";
}
{
#Override
protected Map<String, String> getParams ()throws AuthFailureError {
return params;
}
#Override
public byte[] getBody ()throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse (NetworkResponse response){
String responseString = "";
if (response != null) {
try {
responseString = new String(response.data, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
}
;
requestQueue.add(stringRequest);
}catch(JSONException e){
e.printStackTrace();
}

Categories