What is the best way to save a RequestQueue response? - java

all. First time posting here.
Anyway, I wrote an Android method that creates a RequestQueue and sends a request to my server via a PHP script to get the server time. The way I have it DOES work, but I'm almost certain it's jury rigged code and there must be a better way to do it.
Bottom Line: I want to save the onResponse response into a String time that I can return (time was a String before being changed to an ArrayList). However, it won't let me use a String from outside onResponse unless it is final. Of course that means I can't change it to response.
I think I'm going about it wrong. Maybe there's a better way to get a response from the PHP script?
The Android method:
public static String getServerTime(Context c){
//Make a final ArrayList that will hold response once received
final ArrayList<String> time = new ArrayList<String>();
//Set up the RequestQueue
RequestQueue requestQueue = Volley.newRequestQueue(c);
String requestUrl = c.getString(R.string.uploadServerUrl)+c.getString(R.string.serverRequestPath);
Response.Listener responseListener = new Response.Listener<String>() { #Override public void onResponse(String response) { time.add(response.toString()); System.out.println("onResponse: "+response.toString());}};
Response.ErrorListener errorListener = new Response.ErrorListener() { #Override public void onErrorResponse(VolleyError error) {System.out.println("onErrorResponse: "+error.toString());}};
StringRequest request = new StringRequest(Request.Method.POST, requestUrl, responseListener, errorListener){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("option", "0");
return parameters;
}
};
RetryPolicy retryPolicy = new RetryPolicy(){
#Override public int getCurrentTimeout() {
return 50000;
}
#Override public int getCurrentRetryCount() {
return 50000;
}
#Override public void retry(VolleyError error) throws VolleyError {}
};
request.setRetryPolicy(retryPolicy);
requestQueue.add(request);
return time.remove(0);
}
The PHP script:
<?php
if(isset($_POST["option"])){
$option = $_POST["option"];
switch($option){
case 0:
date_default_timezone_set ("America/Chicago");
$time = time();
echo(date("Y;m;d;H;i;s", $time));
}
}
else{
echo "No option set!";
}
?>

Related

Android Volley not being recognized as POST on server with php

I am using volley to sent post to my server. in my php inside insert.php i have code like this
if($_SERVER['REQUEST_METHOD'] == 'POST'){
//do all post functions
}
else{
//notofication that says its not post
}
This is my volley code in my android
String HttpUrl = "http://192.168.30.18/insert.php";
// Creating string request with post method
StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String ServerResponse) {
// Hiding the progress dialog after all task complete.
progressDialog.dismiss();
// Showing response message coming from server.
Toast.makeText(CreateAccountOrLoginActivity.this, ServerResponse, Toast.LENGTH_LONG).show();
Log.d("responseSuccess",ServerResponse);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
// Hiding the progress dialog after all task complete.
progressDialog.dismiss();
// Showing error message if something goes wrong.
Toast.makeText(CreateAccountOrLoginActivity.this, volleyError.toString(), Toast.LENGTH_LONG).show();
Log.d("responseFail",volleyError.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
// Creating Map String Params.
Map<String, String> params = new HashMap<String, String>();
// Adding All values to Params.
params.put("title",title);
params.put("name", fname);
params.put("surname", sname);
return params;
}
};
// Creating RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(CreateAccountOrLoginActivity.this);
// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);
The problem is after the android code is run, it returns what is in the else statement of the insert.php instead of what is in the if statement, meaning it is not being recognized as a post. How do i resolve it to make it run in the if statement

Why am I getting an error in Hitting API using JSON

While I am hitting API using JSON I am getting the following error I don't know where is my error can anybody help in resolving it as I don't have much knowledge of Json Parsing
public void onPaymentSuccess(String s, PaymentData data) {
String paymentId = data.getPaymentId();
String signature = data.getSignature();
String orderId = data.getOrderId();
callvolly(paymentId,signature,orderId );
}
private void callvolly(final String paymentId,final String signature,final String orderId) {
String tag_json_obj = "json_obj_req";
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("posting...");
pDialog.show();
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = "http://staging.s.com//payment/validate" ;
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getApplicationContext(),"Success",Toast.LENGTH_SHORT).show();
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_SHORT).show();
//This code is executed if there is an error.
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("paymentId", paymentId);
MyData.put("signature", signature);
MyData.put("orderId", orderId);
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
}
java.lang.IllegalArgumentException: Request#getParams() or
Request#getPostParams() returned a map containing a null key or value:
(signature, null). All keys and values must be non-null.
at com.android.volley.Request.encodeParameters(Request.java:478)
at com.android.volley.Request.getBody(Request.java:466)
at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:275)
at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:249)
at com.android.volley.toolbox.HurlStack.executeRequest(HurlStack.java:94)
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:123)
at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:131)
at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:111)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:90)

Make POST request to Api in Android Studio

I'm trying to make a POST request to an api that I have created in Visual Studio. The api works, and I finally managed to find some code that allows me to connect to it (and it's not deprecated). The problem is that this code was made for a GET request while I need to make a POST. I created two boxes where I insert the data I want to pass (utente, password) and I created a button that takes the data from the boxex and convert them to string.
I tried already searching a lot of examples and tutorials that show how to make a POST request but the majority are very old and doesn't work anymore in Android Studio, or at least I can't make them work.
Now, this is the function that should be sending the data, I haven't touched the code since I don't really know what to modify except for the Request Method.
private StringRequest searchNameStringRequest(String utente, String password)
{
String url = "http://192.168.1.11:57279/api/utente";
return new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
try
{
JSONObject result = new JSONObject(response).getJSONObject("list");
int maxItems = result.getInt("end");
JSONArray resultList = result.getJSONArray("item");
}
catch (JSONException e)
{
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(MainActivity.this, "Food source is not responding (USDA API)", Toast.LENGTH_LONG).show();
}
});
}
Can someone explain me how to take the data and send it like a JSON Object that has
keys = user, password
values = utente, password (the values are from the two boxes mentioned before)
Thank to anyone who is willing to help me and I hope that asking for so much help isn't against the site rules.
I'm using Volley since is not so complicated and because it seems to work.
Using the GET method it show me the existing json with message cannot be converted to JSON object (I don't care about that, it's just a confirmation that it connects to the api)
Using the POST method it throws the ErrorResponse at the end (Food source is not responding)
EDIT: Added OnCreate method since I need a StringRequest return
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queue = Volley.newRequestQueue(this);
Button invia = findViewById(R.id.submit);
final EditText utenteInserito = findViewById(R.id.utente);
final EditText passwordInserito = findViewById(R.id.password);
invia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String utente = utenteInserito.getText().toString();
String password = passwordInserito.getText().toString();
queue.cancelAll(R.id.submit);
StringRequest stringRequest = searchNameStringRequest(utente, password);
stringRequest.setTag(R.id.submit);
queue.add(stringRequest);
}
});
}
EDIT: I have followed the suggested answer given but it doesn't seem to work
The resulting code is shown below but I get the OnErrorResponse, I don't think it's a problem with the api because trying with a GET response it gives me the exiting json array, so I think it's a problem with the code.
private StringRequest searchNameStringRequest(final String utente, final String password)
{
String url = "http://192.168.1.11:57279/api/utente";
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
System.out.println(response);
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(MainActivity.this,"Service Unavailable",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams()
{
Map<String,String> map = new HashMap<>();
map.put("user", utente.trim());
map.put("password",password.trim());
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(request);
return request;
}
It's working following this question:
How to send a POST request using volley with string body?
Thanks to you all for your interest.
String url = "your url";
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response);
dialog.dismiss();
try {
// your logic when API sends your some data
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(context,"Service Unavailable",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}){
//This is how you will send the data to API
#Override
protected Map<String, String> getParams(){
Map<String,String> map = new HashMap<>();
map.put("name",username.getText().toString());
map.put("password",password.getText().toString());
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(request);
}
Here is a nice tutorial, I have tried it and it worked seamlessly.
Android Login and Registration with PHP, MySQL and SQLite
You can skip the sqlite and the phpMyAdmin part.

Return a result to same level as the call Volley android

I know there are a few very question that are almost identical, however they are just different enough that I can't get my code to work.
I'm using volley to check if a token is valid and want to be able to store the result at the same level as the call i.e. so as if to simulate Boolean isValid = validToken().
This is what I have so far...
Callback interface
interface VolleyCallback {
void onSuccess(boolean result);
}
Volley function to check token
private void validToken(final String token, final VolleyCallback callback){
String url = "http://example/api/validate_token";
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
callback.onSuccess(true);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
callback.onSuccess(false);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String, String>();
headers.put("Authorization", token);
return headers;
}
};
//Access the RequestQueue through the singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
}
The function call
Boolean tokenIsValid;
validToken("Bearer eyJhbGciOiJ", new VolleyCallback() {
#Override
public void onSuccess(boolean result) {
}
});
All I want to be able to do is store the result of the validToken call in the tokenIsValid variable.
Thanks
In my question I was using a asynchronous volley request and wanting a return value right away. This is wrong, I should have used a synchronous request with a timeout. See this post (Look at the answer about not locking the thread. Asynchronous requests should no be used for things like I was trying to use it for.

Android post request with non key pair

Below is my currently working code to switch on a light with my home automation system. I am upgrading to a new system and it needs a modified post command. Currently I think this sends the key pair "lightswitch1=ON". I need it to only send "ON" but I am not sure how to do this. Below is the CURL command that works.
public void turnonlight() {
String url = "http://example.com:8090/CMD";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(MjpegActivity.this,response,Toast.LENGTH_LONG).show();
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
}
},
new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(MjpegActivity.this,error.toString(),Toast.LENGTH_LONG).show();
//This code is executed if there is an error.
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put(lightswitch1 "ON"); //Add the data you'd like to send to the server.
return MyData;
}
};
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
MyRequestQueue.add(MyStringRequest);
}
curl -X POST --header "Content-Type: text/plain" --header "Accept: application/json" -d "ON" "http://example.com:8090/CMD"
The following should be working with Volley :
String url = "http://example.com:8090/CMD";
StringRequest myStringRequest = 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) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
return headers;
}
#Override
public String getBodyContentType() {
return "text/plain";
}
#Override
public byte[] getBody() throws AuthFailureError {
String httpPostBody = "ON";
return httpPostBody.getBytes();
}
};
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
myStringRequest.setShouldCache(false);
MyRequestQueue.add(myStringRequest);
The body is overriden by getBody() and the specified header with getHeaders().

Categories