I use a HttpPost in my code, where I add the entity like this:
String bodyContent = ".......";
HttpPost httpost = new HttpPost(url);
StringEntity se = new StringEntity(bodyContent);
httpost.setEntity(se);
Now I want to change HttpPost in the Volley Request.
How to set setEntity?
I do not understand how I can insert my string bodyContent.
Should I use another method?
boolean contentType = true/false;
//new post request in to volley
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Error.Response", "OK");
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", "KO");
}
}
) {
//add body content-type
#Override
public String getBodyContentType() {
if (contentType) {
return "application/json; charset=utf-8";
} else {
return "text/plain; charset=utf-8";
}
}
//add header
#Override
public Map<String, String> getHeaders() throws AuthFailureError
{
Map<String, String> params = new HashMap<String, String>();
params.put("VLHASH", "464646");
return params;
}
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("name", "Alif");
params.put("domain", "http://itsalif.info");
return params;
}
};
queue.add(postRequest);
You just need to override getBody() as well like you have overridden getBodyContentType in your StringRequest
Sample Code
String body = "test body";
#Override
public byte[] getBody() throws AuthFailureError {
return body.getBytes();
}
Related
If I send a request with no body everything works. Anyway, when I add the body I get error 400. The body is a JSON converted to String.
Request:
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
key=response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Fail database",Toast.LENGTH_SHORT).show();
Log.d("tuzzo","err: "+error);
}
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SimpleDateFormat myFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.ITALY);
Map<String, String> params = new HashMap<>();
params.put("nameEx", String.valueOf(prefs.getString("exhtitle",null)));
params.put("descrEx", String.valueOf(prefs.getString("exhdescr",null)));
params.put("longDescr", String.valueOf(longdescr.getText()));
params.put("idCategories", String.valueOf(catmap.get(String.valueOf(spin_cat.getText()).toLowerCase())));
try {
params.put("startDate", myFormat.format(myFormat.parse(startDate.getText().toString())));
params.put("endDate", myFormat.format(myFormat.parse(endDate.getText().toString())));
}catch (ParseException e){
Log.e("testdate","error: "+e);
}
params.put("idMuseums", String.valueOf(musmap.get(String.valueOf(spin_mus.getText()).toLowerCase())));
params.put("chiave", String.valueOf(prefs.getString("exhkey",null)));
return params;
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return full == null ? null : full.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
Log.d("volleyuee", "uee: "+uee);
return null;
}
}
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
My server in Python with Flask:
def upd():
data = request.data
if not os.path.exists("/home/tuzzo/stg/res/%s"%request.form['chiave']):
os.makedirs("/home/tuzzo/stg/res/%s"%request.form['chiave'])
os.makedirs("/home/tuzzo/stg/res/%s/download"%request.form['chiave'])
os.makedirs("/home/tuzzo/stg/res/%s/header"%request.form['chiave'])
if not data is None:
with open('/home/tuzzo/stg/res/%s/download/jsonEx.json'%request.form['chiave'], 'w') as outfile:
simplejson.dump(data, outfile)
with open('/home/tuzzo/stg/res/%s/manifest.xml'%request.form['chiave'], 'w') as xmlfile:
xmlfile.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?><channel><item><json>http://tuzzo.pythonanywhere.com/download/"+request.form['chiave']+"/jsonEx.json</json></item></channel>")
addEx(request.form['chiave'])
return request.form['chiave']
If I send the String in parameters and I use data = request.form[value] it works, but I don't know what is missing in this request.
Flask views, by default, only respond to GET requests, unless you have a route decorator that specifies that they should also respond to POST (or any other type). Like this:
#app.route('/something', methods=['GET', 'POST'])
def view():
... view code ...
I'm trying to get access tokens from the server using a volley String request. I have tried making a JsonObjectRequest also. Both are below.
public void getAuthenticationTokens(Object param1, final CustomListener<String> listener)
{
//String url = prefixURL + "this/request/suffix";
String url = "https://lw.xxx.co.uk/connect/token";
StringRequest request = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.e("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.e("Error.Response", error.networkResponse.toString());
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("Content-Type","application/x-www-form-urlencoded");
//..add other headers
return params;
}
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String> ();
params.put("scope", "openid email phone profile offline_access roles");
params.put("resource", "window.location.origin");
params.put("grant_type", "password");
params.put("username", "support#xxx.com");
params.put("password", "tempPxxx");
return params;
}
};
requestQueue.add(request);
.
public void getAuthenticationTokens(Object param1, final CustomListener<String> listener)
{
//String url = prefixURL + "this/request/suffix";
String url = "https://lw.xxx.co.uk/connect/token";
Map<String, Object> jsonParams = new HashMap<>();
jsonParams.put("scope", "openid email phone profile offline_access roles");
jsonParams.put("resource", "window.location.origin");
jsonParams.put("grant_type", "password");
jsonParams.put("username", "support#xxx.com");
jsonParams.put("password", "tempPxxx");
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(jsonParams),
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
Log.d(TAG + ": ", "somePostRequest Response : " + response.toString());
if(null != response.toString())
listener.getResult(response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
if (null != error.networkResponse)
{
Log.e(TAG + ": ", "Error Response code: " + error.networkResponse.statusCode);
listener.getResult(null);
}
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
// Map<String,String> params = super.getHeaders();
// if(params==null)params = new HashMap<>();
Map<String,String> params = new HashMap<>();
params.put("Content-Type","application/x-www-form-urlencoded");
//..add other headers
return params;
}
};
requestQueue.add(request);
.
I get the following response from the server:
E/Volley: [31388] BasicNetwork.performRequest: Unexpected response code 400 for https://lw.xxx.co.uk/connect/token
.
My colleague who has written the server-side code has asked how to convert the following Angular code (his code that works with the API), to Android.
Can anyone help with this?
getLoginEndpoint(userName: string, password: string): Observable<Response> {
let header = new Headers();
header.append("Content-Type", "application/x-www-form-urlencoded");
let searchParams = new URLSearchParams();
searchParams.append('username', userName);
searchParams.append('password', password);
searchParams.append('grant_type', 'password');
searchParams.append('scope', 'openid email phone profile offline_access roles');
searchParams.append('resource', window.location.origin);
let requestBody = searchParams.toString();
return this.http.post(this.loginUrl, requestBody, { headers: header });
}
The problem was a couple of things.
I replaced "params.put("resource", "window.location.origin"); " with "params.put("resource", "https://lw.xxx.co.uk");"
Also, I found out that Volley ignore the getHeaders override, so I commented that method out and used the following to set the headers.
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
public void getAuthenticationTokens(Object param1, final String userName, final String password, final CustomListener<JSONObject> listener)
{
String url = "https://lw.xxx.co.uk/connect/token";
StringRequest request = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.e("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.e("Error.Response", error.networkResponse.toString());
}
}
) {
/* #Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("Content-Type","application/x-www-form-urlencoded");
//..add other headers
return params;
}*/
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String> ();
params.put("scope", "openid email phone profile offline_access roles");
params.put("resource", "https://lw.xxx.co.uk");
params.put("grant_type", "password");
params.put("username", userName);
params.put("password", password);
return params;
}
#Override
protected VolleyError parseNetworkError(VolleyError response) {
try {
String json = new String(response.networkResponse.data, HttpHeaderParser.parseCharset(response.networkResponse.headers));
Log.e(TAG, "reponse error = " + json);
}catch (Exception e){}
return super.parseNetworkError(response);
}
};
requestQueue.add(request);
}//end of getAuthenticationTokens
I'm trying to use KairosAPI's enroll POST request using Android Volley. However I keep getting Error 1002, image one or more required parameters are missing. I've tried two ways to add the parameters into the body of the JSON, which I've outlined in the code.
This is my code-
public class MainActivity extends AppCompatActivity {
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
postRequestToEnrollPersonInGallery();
}
public void postRequestToEnrollPersonInGallery() {
final String appId = "3e12****";
final String appKey = "156e06fd782a3304f085f***********";
String mainUrl = "https://api.kairos.com/";
String enrollRequestUrl = "enroll";
requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, mainUrl + enrollRequestUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Volley", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/json");
params.put("app_id", appId);
params.put("app_key", appKey);
return params;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("image", "https://s-media-cache-ak0.pinimg.com/originals/c6/c0/04/c6c004ec669d92faa36d8ff447884293.jpg");
params.put("subject_id", "12345");
params.put("gallery_name", "FirstGallery");
/*params.put("image", "\"url\":\"https://s-media-cache-ak0.pinimg.com/originals/c6/c0/04/c6c004ec669d92faa36d8ff447884293.jpg\"");
params.put("subject_id", "\"subject_id\":\"12345\"");
params.put("gallery_name", "\"gallery_name\":\"FirstGallery\""); -- i tried this too*/
return params;
}
};
requestQueue.add(stringRequest);
}
}
You aren't posting JSON.
You can either
1) Learn to use JsonObjectRequest
final JSONObject body = new JSONObject();
body.put(... , ...);
Request request = new JsonObjectRequest(url, body, ...);
2) Actually post a JSON String.
StringRequest request = new StringRequest(...) {
#Override
public byte[] getBody() throws AuthFailureError {
JSONObject params = new JSONObject();
params.put("image", "https://s-media-cache-ak0.pinimg.com/originals/c6/c0/04/c6c004ec669d92faa36d8ff447884293.jpg");
params.put("subject_id", "12345");
params.put("gallery_name", "FirstGallery");
return params.toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
I am trying hit an api(written in PHP) and posting params with it.
Here is my code:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, null,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("prerna succes volley "+response.toString());
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("prerna fail volley "+error.toString());
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> pars = new HashMap<String, String>();
pars.put("Content-Type", "application/x-www-form-urlencoded");
return pars;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("action", "login");
params.put("username", "abc#xyz.com");
params.put("pass", "a");
return params;
}
};
I always get invalid username/password which has been handled in api in case there is invalid username and password.In this case api is not receiving the params.
I tried to do it with retrofit and its working fine with it that means there is no problem at API coding. What am I missing here in case of volley?
Thanks for the support. I am able to solve the problem by changing JsonObjectRequest to StringRequest. i found Volley JsonObjectRequest Post parameters no longer work where I got to know that JsonObjectRequest creates some unexpected problems.
There is my code:
StringRequest jsonObjReq = new StringRequest(Request.Method.POST,
url,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response.toString());
String no = jsonObject.getString("$PhoneNo");
} catch (JSONException e) {
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("prerna fail volley " + error.toString());
}
})
{
#Override
public String getBodyContentType() {
Map<String, String> pars = new HashMap<String, String>();
pars.put("Content-Type", "application/x-www-form-urlencoded");
//return pars;
return "application/x-www-form-urlencoded";
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("action", "login");
params.put("username", "abc#xyz.com");
params.put("pass", "a");
return params;
}
};
However I am still trying to figure out why JsonobjectRequest did not work.
As far as I can tell by looking at JsonObjectRequest your 3rd parameter is null, and it indicates the JsonObject request - by the documentation "jsonRequest - A JSONObject to post with the request. Null is allowed and indicates no parameters will be posted along with request."
And after searching again, I saw this thread.
if you are sending your data in raw format you need to try this,first of all make json of your data to be post.
final JSONObject jsonBody = new JSONObject();
jsonBody.put("mobile", phoneNumber);
jsonBody.put("otp", otp.trim());
and you have to override these methods
#Override
public byte[] getBody() throws AuthFailureError {
return jsonBody.toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
if you also have header in your post request you also send that with by following type
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
String auth_token = "bearer" + prefs.getPreferencesString(context, "AuthToken").toString();
params.put("Authorization", auth_token);
return params;
}
Here is the whole code.
final JSONObject jsonBody = new JSONObject();
jsonBody.put("mobile", phoneNumber);
jsonBody.put("otp", otp.trim());
StringRequest sr = new StringRequest(Request.Method.POST, Constraints.Base_URL + "/api/v1/verifyotp", new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
progressDialog.dismiss();
JSONObject jsonObject = new JSONObject(response);
int status = jsonObject.getInt("status");
String token = jsonObject.getString("token");
prefs.setPreferencesString(OtpActivity.this, "AuthToken", token);
if (status == 1) {
startActivity(new Intent(getApplicationContext(), WelcomeScreenActivity.class));
overridePendingTransition(R.anim.right_in, R.anim.left_out);
} else if (status == 0) {
Toast.makeText(OtpActivity.this, "Please Enter Otp!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(OtpActivity.this, "Invalid otp please try again!!", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
return jsonBody.toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
MyApplication.getInstance().addToReqQueue(sr, "jreq");
}
} catch (Exception e) {
}
Try migrating to getHeaders and remove getParams
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("action", "login");
params.put("username", "abc#xyz.com");
params.put("pass", "a");
return pars;
}
Or - Reuse the getParams method
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = getParams();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
If it is a body request all you need to do is add the extra parameter.
JSONObject body = new JSONObject();
body.put("action", "login");
body.put("username", "abc#xyz.com");
body.put("pass", "a");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, body,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("prerna succes volley "+response.toString());
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("prerna fail volley "+error.toString());
}
});
This is the first time I'm working with JSON but I'm experimenting with POST requests.
I want to make a POST request to this website http://jsonblob.com/api
My code works when I use an asynctask + httppost
private static final String url = "http://jsonblob.com/api/jsonBlob";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new PostJsonTask().execute();
}
private class PostJsonTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
HttpResponse response = post();
Header s = response.getFirstHeader("Location");
Log.d("PostJsonTask", s.getValue());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private HttpResponse post() throws Exception {
// convert parameters into JSON object
Map<String, String> params = new HashMap<String, String>();
params.put("user", "Robby");
params.put("pass", "zqdqzdqdqzd");
JSONObject holder = new JSONObject(params);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
StringEntity se = new StringEntity(holder.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
post.setEntity(se);
return client.execute(post);
}
}
With this code I can succesfully get the Location parameter.
But I want to do this with the Volley library, I already have the following code :
private static final String url = "http://jsonblob.com/api/jsonBlob";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST, url, createResponseListener(), createErrorListener()) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
headers.put("Content-type", "application/json");
return headers;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("user", "Robby");
params.put("pass", "zqdqzdqdqzd");
return params;
}
#Override
protected Response<String> parseNetworkResponse(
NetworkResponse response) {
Map<String, String> headers = response.headers;
String location = headers.get("Location");
Log.d("PostJsonTask", location);
return super.parseNetworkResponse(response);
}
};
queue.add(request);
}
private ErrorListener createErrorListener() {
return new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
};
}
private Listener<String> createResponseListener() {
return new Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("PostJsonTask", response);
}
};
}
But this returns a VolleyError with code 400. How can I fix this?
Instead of trying to set Content-type of header try to set for bodyContentType and in postman(web) also you are setting the content type of body only
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
url, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.toString());
}
})
#Override
public String getBodyContentType() {
return "application/json";
}
};
Don't use the getParams override.
Instead, create a JSON with these parameter and provide as the body of the request like they do in JsonObjectRequest (or just use a JsonObjectRequest instead of a StringRequest), e.g.
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("user", "Robby");
jsonObject.put("pass", "zqdqzdqdqzd");
} catch (JSONException e) {
// handle exception (not supposed to happen)
}
StringRequest request = new StringRequest(Request.Method.POST, url, createResponseListener(), createErrorListener()) {
// your code without getParams
#Override
public byte[] getBody() {
try {
return jsonObject.toString.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
// not supposed to happen
return null;
}
}
}