Make POST request to Api in Android Studio - java

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.

Related

why isn't Volley sending the variables in getParams()?

I'm Trying to list machines which are related to the user of the application by sending the username and password to the webpage mentioned in the code verifying the account and then sending back the information of the machines in my database.
the PHP well but the username and password are not being sent.
here is the code for the request:
private void getServerResponse(String username,String password) throws IOException {
String urlS = "http://10.0.2.2/send/sendmachines.php";
RequestQueue RQ= Volley.newRequestQueue(this);
JsonArrayRequest array_request = new JsonArrayRequest(Request.Method.POST, urlS, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
TextView proof =findViewById(R.id.proof);
for(int i=0; i<response.length(); i++){
try {
proof.setText(response.getJSONObject(0).getString("machine_id"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
TextView proof =findViewById(R.id.proof);
proof.setText(error.getMessage());
}
}){
protected Map<String,String> getParams(){
Map<String,String > params = new HashMap<>();
params.put("username",username);
params.put("password",password);
return params;
}
};
RQ.add(array_request);
}
the username and password were already used to log in and sent as extras to this activity.
in the end it turned out that the code isn't passing through the getParams() so i turned it to a string request and parsed the response string into a jsonArray.
i couldn't find much information about it online so IDK why all this isn't working and i cant consider this an answer so it's more of an update.

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

Volley String Response of XML data and parse xml data

Following is my approach:
private void liveScores(){
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
if(requestQueue == null)
{
requestQueue = Volley.newRequestQueue(LiveScores.this);
}
requestQueue.add(stringRequest);
}
What I want is that i'm getting this response in string and this is xml data. I'm not able to use xmlpullparse in this. Can any one tell me how to make it async means these are live scores data and how to keep it refreshing after a while and also how to get objects of this response differentiate.
this is link of xml response and i want to get title element and put it in Listview.
Any help will be appreciated thanks.

What is the best way to save a RequestQueue response?

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!";
}
?>

Volley library dosent connect to server in some devices

in first i'm use Httpurlconnection and have same issue(Dosent find my Url in server in some devices and other device conncet easy) and i think bug e Httpurlconnection and i decide use Volley and same issue exist when use that
Error:
com.android.volley.VolleyError:java.lang.NullPointerException
Volley Code :
StringRequest postRequest = new StringRequest(Request.Method.POST, uri,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("HOOOO", response);
progressDialog.dismiss();
try {
JSONObject jsonobj = new JSONObject(response);
int success = Integer.parseInt(jsonobj.getString("success"));
String msg = jsonobj.getString("message");
check(Flag,success,msg,pass,email);
}catch (Exception e){
Snackbar snackbar1 = Snackbar.make(Mainlayout,e.toString(), Snackbar.LENGTH_LONG);
snackbar1.show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Log.i("Error Respone", error.toString());
Snackbar snackbar1 = Snackbar.make(Mainlayout,error.toString(), Snackbar.LENGTH_LONG);
snackbar1.show();
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
if(Flag=="Insert") {
params.put("email", email);
params.put("fact", DeviseBrand);
params.put("model", DeviseModel);
}else if((Flag=="signin") ||(Flag=="update") ){
params.put("email", email);
}
// the POST parameters:
return params;
}
};
postRequest.setRetryPolicy(new DefaultRetryPolicy(
9000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(this).add(postRequest);
and my uri :
http://domain.com/App/Register.php
Post data and on server get with _Request[];
Volley is a very strong API, i don't think they could have such an issue, check your code maybe in some cases it doesn't initialize the object correctly.
I used Volley for more than 1 year and didn't had such issue.
1-check that you are using the latest release from this link.
2-put your code in question so we can check it with you, also the log could be helpful to trace the issue, also what is the device you are using ?

Categories