Guys i need help am trying to post this data to my server here but it is returning an error, it seems to be working just fine in postman the problem comes in while trying to implement in android app using google's volley library.
Link to server script.
This is the screenshot of a successful post working in postman rest client:2
private void SaveDataToServer() {
StringRequest serverPostRequest = new StringRequest(Request.Method.POST, Config.SAVE_INVENTORY_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String json) {
try {
Toast.makeText(SelectItemsActivity.this, json.toString(), Toast.LENGTH_SHORT).show();
Log.e("RESPONSE FROM SERVER",json);
JSONObject dataJson=new JSONObject(json);
JSONObject myJson=dataJson.getJSONObject("status");
String status=myJson.getString("status_text");
if (status.equalsIgnoreCase("Success.")){
Toast.makeText(SelectItemsActivity.this, "Data saved Successfully", Toast.LENGTH_SHORT).show();
proggressShow.dismiss();
}else {
Toast.makeText(SelectItemsActivity.this, "An error occured while saving data", Toast.LENGTH_SHORT).show();
proggressShow.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}){
#Override
protected Map<String, String> getPostParams() {
HashMap<String, String> params = new HashMap<String, String>();
params.put("api_key",Config.API_KEY);
params.put("move_id", "1");
params.put("room_name", "Attic room");
params.put("item_name", "Halloween Broom");
params.put("item_id", "6");
Log.e("datat to server",params.toString());
return params;
}
};
saveDataRequest.add(serverPostRequest);
}
Try adding getHeaders method in your request
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
final HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "multipart/form-data");
return headers;
}
After adding this lines to my request headers i was able to successfully commit the database to my db.
Also i made sure i am using a stringRequest for a jsonRequest it does not work for reasons i do not know.
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type","application/x-www-form-urlencoded");
return headers;
}
Related
I want to send Array to server that looks like this :
"Array":["name"="something", "description"="something"]
To perform request i'm using this method :
private void saveNote(final int id, final String name, final String des, final String assing) {
Log.d(TAG, "Saving");
StringRequest stringRequest = new StringRequest(Request.Method.POST, Api.URL_CREATE_NOTE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response.toString());
try {
JSONObject obj = new JSONObject(response);
if (!obj.getBoolean("error")) {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> postParams = new HashMap<>();
Map<String, String> tableData= new HashMap<>();
tableDataParam.put("name",name);
tableDataParam.put("description",des);
postParams.put("Array[]", tableDataParam.toString());
return params;
}
};
VolleySingletonNotes.getInstance(context).addToRequestQueue(stringRequest);
}
First issue is that i can pass only String in postParams HashMap, so when i do tableData.toString the tableData have string brackets like this:
"Array":["{name=something, desciption=something}"]
And the second issue is that tableData HashMap for some reason dont put his String parameters in string brackets as you can see in example below first issue.
I already tried make JsonArray that fix the second issue but the first issue still remains, plus it automatically create backslashes(they dont show when i type them here)
Can anyone help me with this issue? Thanks.
I want to update the "Pass" field using WebAPI, I have created an HTTP PUT Request using Asp.Net WEB API and Android Java with Volley.
through Postman it's updating field value but when I test through my App it's updating the blank value in DB.
Thanks in advance.
private void callPUTDataMethod(String name, String job) {
loadingPB.setVisibility(View.VISIBLE);
String url = URL;
RequestQueue queue = Volley.newRequestQueue(PassUpdt.this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.PUT, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
loadingPB.setVisibility(View.GONE);
jobEdt.setText("");
userNameEdt.setText("");
// on below line we are displaying a toast message as data updated.
Toast.makeText(PassUpdt.this, "Data Updated..", Toast.LENGTH_SHORT).show();
try {
JSONObject jsonObject = new JSONObject("Pass");
String output = "Password Updated";
responseTV.setText(output);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(PassUpdt.this, "Fail to update data..", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("EmpCd", "P010");
params.put("Pass", "12345");
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
};
queue.add(jsonObjectRequest);
}
}
I'am trying to call an API that adds data to a dynamoDB each time a user creates an account .
The url of the API is in the following format :
https://t3x9lg8utf.execute-api.us-east-2.amazonaws.com/prod? id=""&username=""&numero_passeport=""&decision=""
The problem is that when i call the API using volley i get this error :
06-03 14:32:23.599 13503-14515/com.amazonaws.youruserpools.CognitoYourUserPoolsDemo E/Volley: [14796] BasicNetwork.performRequest: Unexpected response code 400 for https://t3x9lg8utf.execute-api.us-east-2.amazonaws.com/prod
The code i used to call the API :
StringRequest sr = new StringRequest(Request.Method.GET, "https://t3x9lg8utf.execute-api.us-east-2.amazonaws.com/prod",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("HttpClient", "success! response: " + response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("HttpClient", "error: " + error.toString());
}
})
{
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("id","\"\"");
params.put("username","\"zaeae\"");
params.put("numero_passeport","\"\"");
params.put("decision","\"\"");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
return params;
}
};
queue.add(sr);
try this
StringRequest sr = new StringRequest(Request.Method.GET, "https://t3x9lg8utf.execute-api.us-east-2.amazonaws.com/prod?id="+Uri.encode(id)+"&username="+Uri.encode(username)+"&numero_passeport="+Uri.encode(numero_passeport)+"&decision="+Uri.encode(decision),
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("HttpClient", "success! response: " + response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("HttpClient", "error: " + error.toString());
}
})
{
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("id","\"\"");
params.put("username","\"zaeae\"");
params.put("numero_passeport","\"\"");
params.put("decision","\"\"");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
return params;
}
};
queue.add(sr);
also pass values for id, username, numero_passeport and decision
? id=""&
These are URL parameters, which cannot be passed via getParams()
You need to append them to the string after Request.Method.GET
I've setup a MySql server with a RESTful api to handle my login/signup system for my android app.
I'm creating an ASyncTask to handle the signup POST request, the server should return a JSON object telling us whether it was successful or not. When I input valid details and register on my Android app, the first response in onPostExecute is null. I press the button again and it is correct. What could I be doing wrong?
private class PostAndReadResponseTask extends AsyncTask<Account, Void, String> {
#Override
protected String doInBackground(Account... accounts) {
final Account thisAccount = accounts[0];
RequestQueue requestQueue = Volley.newRequestQueue(RegisterActivity.this);
final String signupURL = "http://localhost:8080/fitnessTrack/api.php?apicall=signup";
StringRequest stringRequest = new StringRequest(Request.Method.POST, signupURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
responseJSON = response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley Error:", error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("username", thisAccount.getUsername());
params.put("password", thisAccount.getPassword());
params.put("email", thisAccount.getEmail());
params.put("firstname", thisAccount.getFirstName());
return params;
}
};
requestQueue.add(stringRequest);
return responseJSON;
}
#Override
protected void onPostExecute(String result) {
System.out.println(result);
}
}
FYI: I edited the URL to say localhost, even though I'm using my own external IP. Even when the response is null, the database does update with the signup data.
The responseJSON is only updated here
#Override
public void onResponse(String response) {
responseJSON = response; // update UI using responseJSON in here
}
so it won't be ready until that method is called with the response. Try printing in there and it should work
I would like to send and receive a Json Array with volley.
Now I can receive an array and it's ok but I don't know how to send a request (For example: with post method).
JsonArrayRequest arrayReq = new JsonArrayRequest(URL,
new Listener<JSONArray>() {
}
List<Map<String,String>> listMap = new ArrayList<Map<String, String>>();
Map<String,String> map = new HashMap<String,String>();
try {
map.put("email", customer.getEmail());
map.put("password",customer.getPassword());
} catch (Exception e) {
e.printStackTrace();
}
listMap.add(map);
String url = PersonalConstants.BASE_URL+"/url";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST, url, String.valueOf(new JSONArray(listMap)),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.d(App.TAG, jsonObject.toString());
}
}, new Response.ErrorListener (){
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(App.TAG,volleyError.toString());
}
}
);
App.getInstance().getmRequestQueue().add(jsonObjectRequest);
Here is an example:
// Define the web service URL
final String URL = "http://www.someurl.com";
// POST params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "raha tamjid");
// Define the POST request
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// Add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);
How the POST request differs is that it takes a JSONObject as parameter.
EDIT 1:
If you have Volley installed as a library project in your IDE, then just define a new constructor
public JsonArrayRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONArray> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener);
}
inside the class JsonArrayRequest which is present in the Volley library code. Now you can use this to create JsonArrayRequest objects and add them to the RequestQueue.
EDIT 2:
1. Get the Volley library project from here. Download the project and set it up in your IDE.
2. Make the modification to the JsonRequest class (found in com.android.volley.toolbox namespace) as discussed in EDIT 1.
3. Delete the volley.jar from the libs folder of your APPLICATION PROJECT.
4. Now go to Project Properties -> Android -> Library and click on Add. From here select the Volley project. Clean & Rebuild.
5. Now in your APPLICATION PROJECT you can make a POST JsonArrayRequest just like how we make a POST JsonObjectRequest and get a JSONArray in the Response.
Create a class and extend JsonArrayRequest then override
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "value");
return params;
}
and add a new constructor and in it call
super(Method.POST, url, null, listener, errorListener);
or use this class
public class PostJsonArrayRequest extends JsonRequest<JSONArray> {
/**
* Creates a new request.
* #param url URL to fetch the JSON from
* #param listener Listener to receive the JSON response
* #param errorListener Error listener, or null to ignore errors.
*/
public PostJsonArrayRequest(String url, Response.Listener<JSONArray> listener, Response.ErrorListener errorListener) {
super(Method.POST, url, null, listener, errorListener);
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "value");
return params;
}
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONArray(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
Create a new java class named JsonArrayPostRequest now you can use it like the previous request, just replace JSONArrayRequest with JsonArrayPostRequest and pass the correct parameters
public class JsonArrayPostRequest extends Request<JSONArray>{
private Map<String,String> mParam;
private Listener<JSONArray> mListener;
public JsonArrayPostRequest(String url,Listener<JSONArray> listener, ErrorListener errorListener,Map param) {
super(Request.Method.POST, url, errorListener);
mListener=listener;
mParam=param;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return mParam;
}
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONArray(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONArray response) {
mListener.onResponse(response);
}
}
USE:
JsonArrayPostRequest request = new JsonArrayPostRequest(URL,new Response.Listener<JSONArray>(),
new Response.ErrorListener() ,params);