Pass Parameter with Volley POST
The server code is expecting a JSON object is returning string or rather Json string.
JsonObjectRequest
JSONRequest sends a JSON object in the request body and expects a JSON object in the response. Since the server returns a string it ends up throwing ParseError
StringRequest
StringRequest sends a request with body type x-www-form-urlencoded
but since the server is expecting a JSON object. You end up getting 400 Bad Request
The Solution
The Solution is to change the content-type in the string request to JSON and also pass a JSON object in the body. Since it already expects a string you response you are good there. Code for that should be as follows.
StringRequest sr = new StringRequest(Request.Method.POST, Constants.CLOUD_URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
mView.showMessage(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mView.showMessage(error.getMessage());
}
}) {
@Override
public byte[] getBody() throws AuthFailureError {
HashMap<String, String> params2 = new HashMap<String, String>();
params2.put("name", "Val");
params2.put("subject", "Test Subject");
return new JSONObject(params2).toString().getBytes();
}
@Override
public String getBodyContentType() {
return "application/json";
}
};
Also there is a bug here in the server code
var responseMessage = $"Hello {personToGreet}!";
Should be
var responseMessage = $"Hello {name}!";
Sending Parameters in a POST request using Volley
Workaround:
Use this Library and this code:
https://github.com/amitshekhariitbhu/Fast-Android-Networking
void pushMagnet(final String apiKey, final String magnetLink, final Context context) {
final String url = "https://premiumize.me/api/transfer/create?apikey=" + apiKey;
JSONObject srcMagnet = new JSONObject();
try {
srcMagnet.put("src", magnetLink);
} catch (JSONException e) {
e.printStackTrace();
}
OkHttpClient client = new OkHttpClient().newBuilder()
.addInterceptor(new GzipRequestInterceptor()).build();
AndroidNetworking.initialize(context, client);
AndroidNetworking.post(url)
.addHeaders("accept", "application/json")
.addHeaders("Content-Type", "multipart/form-data")
.addQueryParameter("src", magnetLink)
.build().getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject response) {
Log.e("Server response:", response.toString());
}
@Override
public void onError(ANError anError) {
Log.e("Server error:", anError.toString());
}
});
}
Volley - POST/GET parameters
In your Request class (that extends Request), override the getParams() method. You would do the same for headers, just override getHeaders().
If you look at PostWithBody class in TestRequest.java in Volley tests, you'll find an example.
It goes something like this
public class LoginRequest extends Request<String> {
// ... other methods go here
private Map<String, String> mParams;
public LoginRequest(String param1, String param2, Listener<String> listener, ErrorListener errorListener) {
super(Method.POST, "http://test.url", errorListener);
mListener = listener;
mParams = new HashMap<String, String>();
mParams.put("paramOne", param1);
mParams.put("paramTwo", param2);
}
@Override
public Map<String, String> getParams() {
return mParams;
}
}
Evan Charlton was kind enough to make a quick example project to show us how to use volley.
https://github.com/evancharlton/folly/
how to pass parameters with Volley GET method
You can set GET volley request like this
StringRequest commonRequest = new StringRequest(Request.Method.GET, url/* URL OF WEBSERVICE*/, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//HANDLE RESPONSE
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle your error types accordingly.For Timeout & No
// connection error, you can show 'retry' button.
// For AuthFailure, you can re login with user
// credentials.
// For ClientError, 400 & 401, Errors happening on
// client side when sending api request.
// In this case you can check how client is forming the
// api and debug accordingly.
// For ServerError 5xx, you can do retry or handle
// accordingly.
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("KEY","VALUE");
return hashMap;
}
};
commonRequest.setRetryPolicy(new DefaultRetryPolicy(5000, 1, 2));
INSTANCE OF VOLLEY.addToRequestQueue(commonRequest);
This portion of code is useful for you
{
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("KEY","VALUE");
return hashMap;
}
Pass params Using GET method using volley library
As suggested by @Puneet worked for me which is as :
getParams
is only called for POST
requests. GET
requests don't have a body and hence, getParams
is never called. For a simple request like yours just add the parameters to your URL
and use that constructed URL
to make that request to your server (REG_URL + "?email=" + email)
.
How to use POST request in android Volley library with params and header?
**Try this one **
private void sendWorkPostRequest() {
try {
String URL = "";
JSONObject jsonBody = new JSONObject();
jsonBody.put("email", "abc@abc.com");
jsonBody.put("password", "");
jsonBody.put("user_type", "");
jsonBody.put("company_id", "");
jsonBody.put("status", "");
JsonObjectRequest jsonOblect = new JsonObjectRequest(Request.Method.POST, URL, jsonBody, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), "Response: " + response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
onBackPressed();
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
final Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Basic " + "c2FnYXJAa2FydHBheS5jb206cnMwM2UxQUp5RnQzNkQ5NDBxbjNmUDgzNVE3STAyNzI=");//put your token here
return headers;
}
};
VolleyApplication.getInstance().addToRequestQueue(jsonOblect);
} catch (JSONException e) {
e.printStackTrace();
}
// Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_LONG).show();
}
}
Related Topics
Opening Infowindow Automatically When Adding Marker Google Maps V2 Android
Android - How to Set an Alarm to a Specific Date
Camera in Android, How to Get Best Size, Preview Size, Picture Size, View Size, Image Distorted
R.Java Disappears After Project Clean
Intent Putextra Arraylist<Namevaluepair>
Android: Subscribe to Firebase Cloud Messaging(Fcm) Topic
Rotate Zoom Drag Image in Android Imageview
Changing Gradient Background Colors on Android at Runtime
Firebase Authentication Not Working in Signed APK
Screen Overlay Detected Blocks Android Permissions
Kitkat Kills: Not Allowed to Load Local Resource: File:///Android_Asset/Webkit/Android-Weberror.Png
Android Maps API V2 Draw Circle
How to Get the Key from the Value in Firebase
Crop Video Before Encoding with Mediacodec for Grafika's "Continuous Capture" Activity
Searchview Getactionview Returning Null
Searchview in Optionsmenu Not Full Width
How to Send File from Android Device to Other Device Through Bluetooth by Code
My Android Camera Uri Is Returning a Null Value, But the Samsung Fix Is in Place, Help