Sending a POST request with Volley to PHP Script - java

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

Related

AuthFailureError on a volley form data response

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

Android Volley: BasicNetwork.performRequest: Unexpected response code 400

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
}

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

Activity keeps restarting when I leave the activity and come back to it

I have two activities, When I will move from activity A to B, B keeps restarting or "refreshing", when i go back from B to A, it also keeps restarting. The code is very big, here I am posting area where I think problem causes :
Thread t = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
deviceStatus();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();
this is deviceStatus();
public void deviceStatus(){
try {
RequestQueue requestQueue = Volley.newRequestQueue(InActivate.this);
String URL = "http://gickuwait-dev.com/electionapi/api/DeviceStatus";
JSONObject jsonBody = new JSONObject();
jsonBody.put("device_PK", device_ID2);
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.equals("true")){
Intent intent = new Intent(InActivate.this, Vote.class);
startActivity(intent);
finish();
}else if(response.equals("false")) {
}
// Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString;
String json = null;
try {
json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
responseString = String.valueOf(json).trim();
ArrayList<DeviceStatusResponse> list = new ArrayList<DeviceStatusResponse>();
Type listType = new TypeToken<List<DeviceStatusResponse>>() {}.getType();
list = new Gson().fromJson(responseString, listType);
device_Status = list.get(0).getIsActive().toString();
// Toast.makeText(getApplicationContext(), ""+device_Status+" null ", Toast.LENGTH_LONG).show();
return Response.success(device_Status, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
in Activity B, i have the same code to check the device status from the database, any help would be appreciated
You can use Handle to check the repeated task.
private Handler delayHandler = new Handler();
private Runnable runnable = new Runnable() {
#Override
public void run() {
deviceStatus();
driverDelayHandler.postDelayed(runnable, 1000);
}
};
Don't forgot to cancel on onStop method.
delayHandler.removeCallbacks(runnable);

Categories