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)
Related
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.
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.
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().
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!";
}
?>
I have the below request but for some reason the headers aren't being "attached" to the request? Please could you maybe assist me with this?
public void get(String servicesUrl, String end_tag_url) {
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url + servicesUrl + end_tag_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("header1", "value");
params.put("header2", "value");
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
I get connection to the server but the is an auth failure because the headers aren't being implemented in the connection.
I have tested on a Chrome add-on called Advanced-Rest-Client and added the headers which worked.
I could add 2 of the headers to the URL but the 3rd one cannot be attached to the URL and needs to be a header?
When creating a request, override getHeaders(), like so:
new JsonObjectRequest(url, jsonRequest, listener, errorListener) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> map = new HashMap<String, String>();
map.put("X-REST-API-Key", resources.getString(R.string.parse_api_key));
map.put("X-Application-id",
resources.getString(R.string.application_id));
if (sessionToken != null) {
map.put("X-Session-Token", sessionToken);
}
return map;
}
};