android volley RequestQueue . code in php - java

I am setting up a sign in page for Android.
Android request code:
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest sr = new StringRequest(Request.Method.POST,"http://www.MY-URL.ir/signup.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("--------------> res : " + response + " <------------------- res");
Toast.makeText(Main2Activity.this, "res", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Main2Activity.this, "-----------------> err", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("name","David Lee");
return params;
}
};
queue.add(sr);
PHP auntification code:
<?php
if(isset($_POST['name']))
{
$name=$_POST['name'];
$response = array();
$response['name'] = $name;
echo json_encode($response);
} else {
$no_data=array();
$no_data['none']= 'no data received';
echo json_encode($no_data);
}
?>
I am sending David Lee as a name and I want to insert it in a database (MySQL)
params.put("name","David Lee");
But I can't recognize the result of the request in my Php MySql table.
Is my code right?
Authentication request returns the following response:
System.out: --------------> res : <html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("1ab6d8dc093d812e09e8e3d3ffcb99d5");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="http://www.papyrusmarket.ir/signup.php?i=1";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html> <------------------- res
How should back-end send the response to android? And how can I get it?

Related

E/Volley: [2342] NetworkUtility.shouldRetryException: Unexpected response code 400

I'm using the Android volley library and I'm trying to sending data to the API server but it responds to this error every time
E/Volley: [2342] NetworkUtility.shouldRetryException: Unexpected response code 400 for API
This is my code:
JSONObject params = new JSONObject();
try {
params.put("deptcode", 649);
params.put("endDt", "2021-07-22T12:37:28.755Z");
params.put("instCode", 152);
params.put("instSesNO", 0);
params.put("locCode", 2);
params.put("observedBy", obserName);
params.put("sessionId", 0);
params.put("startDt", "2021-07-22T12:37:28.755Z");
params.put("status", "string");
}
catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
#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.setRetryPolicy(new DefaultRetryPolicy(300000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MyRequestQueue.add(jsonObjReq);
I tried many ways but still doesn't work for me. Please help me.
normally 400 is a server error that is something not found on server.
1- try your api on postman and verify it is working.
2- sometimes, the value we're passing in int can be resolved by converting them to string.
3- try to get the error message from error.getMessage().
if not resolved, please share your api i'll check.

How to handle 403 error to calling SharePoint list from android?

I want to call SharePoint rest API form android. for this, i'm using cookies to call rest API using web view, but while calling am getting "BasicNetwork.performRequest: Unexpected response code 403".
if l call to SharePoint rest api using volley here what i tried up to.
update:i'm using this site for refrence SharePoint rest api from android
**Update:during research i found one example to connect with share point online using soap as well, any idea how to do that? **
private void sendAndRequestResponse() {
//RequestQueue initialized
Log.d(TAG, "Starting volley request to graph");
/* Make sure we have a token to send to graph */
RequestQueue queue = Volley.newRequestQueue(this);
JSONObject parameters = new JSONObject();
try {
parameters.put("key", "value");
} catch (Exception e) {
Log.d(TAG, "Failed to put parameters: " + e.toString());
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url,
parameters,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
/* Successfully called graph, process data and send to UI */
Log.d(TAG, "Response: " + response.toString());
Toast.makeText(MainActivity.this, ""+response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Cookie","rtFa=" + RTFA + "; FedAuth=" + FedAuth);
headers.put("Accept","application/json;odata=verbose");
headers.put("Content-type","application/json;odata=verbose");
return headers;
}
};
Log.d(TAG, "Adding HTTP GET to Queue, Request: " + request.toString());
request.setRetryPolicy(new DefaultRetryPolicy(
3000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
}
I used rtfa and fed cookies to pass as header.
Update: i used share point login URL for windows auth. for and after success i store rfta and fed auth. cookies to pass token as header but i'm getting same error.

Android can not send post request with volley(BasicNetwork.performRequest: Unexpected response code 404)

I am trying to send some info to my api with post method(volley), but keep getting errors. Most consistent and the latest one is
E/Volley: [1449] BasicNetwork.performRequest: Unexpected response code 404 for http://....
D/Error.Response: com.android.volley.ClientError
I am able to post it with postman but not in android. I am sure nothing is wrong in the other side. I don't know what to do.
I have tried several implementations with getheader(),getBodyContentType(), Json object, string, parsing, try catch and so on..
RequestQueue queue = Volley.newRequestQueue(this);
String url = "....";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
Log.d("Error.Response", error.toString());
}
}
) {
#Override
public Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("email", "test#email.com");
params.put("token", "token");
return params;
}
};
queue.add(postRequest);

PHP-array to Java Arraylist using Volley

I am trying to convert a PHP-array into a Java ArrayList.
I have this PHP-Code which seems to have no syntax errors:
$password = "xxxx";
$host = "localhost";
$db_name = "xxxx";
$output = array();
$con = mysqli_connect("$host", "$user", "$password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (!mysqli_select_db($con, $db_name)) {
die('Could not select database: ');
}
$result = mysqli_query($con, "SELECT name FROM shopping_items"); //change to "name"
if (!$result) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
while($row = mysqli_fetch_array($result, MYSQLI_BOTH))
{
$output[]=$row;
}
return $output;
mysqli_close($con);
?>
It takes one row from the table, so I should get back a PHP-array.
Now comes the hard part. In Java, I wrote the following code using the Volley library:
public void getShopping(String url) {
//init queue or get from somewhere
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest;
stringRequest = new StringRequest(Request.Method.GET, url, //URL leads to PHP-File
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
shoppingItems.add(response); //shopping Items is an ArrayList
adapter.notifyDataSetChanged();
Toast.makeText(ShoppingListActivity.this, response, Toast.LENGTH_SHORT);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//got error
}
});
queue.add(stringRequest);
}
I want to have each item added to shoppingItems. But when printing the array out I get an empty string. I think that StringRequest is the wrong way to go but I don't know any other way. I read that using json_encode is possible but that seems unnecessarily complicated to me. Is there an easier way to do that?
I could not find an answer in previous SO questions. If at all possible, please provide help that involves Volley because it is pretty integrated in my code.

Retrieve JSON from URL by sending 2 variables from my android app in java

im trying to post 2 variables (1 int, 1 string) from my android app on a url and get back JSON response. Actually im doing the same on a website and i want to do it also in my android app.
Code on website:
$.ajax({'
type: "POST",
url: "my url", //my url
data: JSON.stringify({"number": number,"day":"MONDAY"}), //number is an integer and day is a string variable
contentType: "application/json;",
dataType: "json",
success: function (msg) {
}
error: function (jxhr) {
//do some thing
},
complete: function (msg) {
var text = msg.responseText
var obj = JSON.parse(text);
}
Can anyone please help me to do the same thing in java for android using android volley or any other way?
Thank you!
Try to implement a singleton stringrequest or json request. Use HashMap to put your parameters.
StringRequest postReq = new StringRequest(Request.Method.POST, urlPost, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// do your thing
String text = response;
}}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error response
}){
#Override
protected Map<String, String> getParams()
{Map<String, String> params = new HashMap<>();
// the POST parameters:
params.put('number', number);
params.put('day', 'MONDAY');
return params;}
};
Volley.newRequestQueue(getApplicationContext()).add(postReq);

Categories

Resources