I get the following error:
AuthFailureError: com.android.volley.AuthFailureError
My code:
public void createNoticeBoard() {
RequestQueue queue = Volley.newRequestQueue(mContext);
StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConfig.PENDING_MEDIA_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject stringResponse = new JSONObject(response);
boolean success = stringResponse.getBoolean("is_success");
String requestCode = stringResponse.getString("status_code");
if (success) {
if (requestCode.equals("200")) {
Toast.makeText(mContext, "Publisher deleted!", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(mContext, "Unauthorized!", Toast.LENGTH_LONG).show();
}
} catch (JSONException je) {
je.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.e(TAG, "AuthFailureError: " + error);
Toast.makeText(mContext, "Error! Please try again.", Toast.LENGTH_LONG).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> parameter = new HashMap<>();
Log.d("Network", parameter.toString());
return parameter;
}
#Override
protected Map<String, String> getParams() {
Map<String,String> params = new HashMap<String, String>();
params.put("extension", "image/jpeg");
params.put("duration", String.valueOf(20));
params.put("title", "Postman Highlight");
params.put("organization_id", String.valueOf(274));
params.put("screen_type", "TAGNOTICEBOARD");
params.put("type", "IMAGE");
params.put("do", String.valueOf(7));
params.put("advertise_bit", String.valueOf(1));
params.put("start_datetime", "2021-05-06 10:37:13");
params.put("end_datetime", "2021-05-10 10:37:13");
params.put("Global_Counter", String.valueOf(0));
params.put("Venue_Counter", String.valueOf(0));
params.put("adindex", String.valueOf(0));
params.put("adtype", "Fulltime");
params.put("media_url", "");
return params;
}
#Override
public byte[] getBody() throws AuthFailureError {
final String request = getParams().toString();
Log.e("REQ", request);
try {
return request.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", request, "utf-8");
return null;
}
}
};
queue.add(stringRequest);
}
Related
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
}
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;
}
};
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);
}
}
String request return null output in android studio when i used jsonobject request it will give correct output.
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
Log.d(TAG, " url=" + URL);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, " response=" + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, " error=" + error);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
LinkedHashMap<String, String> linkmap = new LinkedHashMap<>();
linkmap.put("p_ENTITY_ID", "2");
linkmap.put("p_ORGCD", "p01");
linkmap.put("p_COMPCD", "A0002");
linkmap.put("p_DIVCD", "");
linkmap.put("p_USERID", "");
linkmap.put("p_ACDYR", "");
linkmap.put("p_TYPE", "ACDYR_DDL");
linkmap.put("p_FILTER1", "");
linkmap.put("p_FILTER2", "");
linkmap.put("p_DEFUNCT", "");
Log.d(TAG, " MAP=" + linkmap);
return linkmap;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
LinkedHashMap<String, String> headers = new LinkedHashMap<>();
return headers;
}
};
requestQueue.add(stringRequest);
}
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();
}