Android AWS: Alternative ways to post things to endpoints - android

I'm new to AWS, I'm looking for an alternative recommended way instead of using Volley to post something to an aws endpoint. The current code, I'm trying to post a comment:
public void submitComment(final Comments comment,
final RequestListener submissionListener) throws JSONException {
String url = this.baseURLPath + "topics/topicId/comments";
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.serializeNulls();
Gson googleGSON = gsonBuilder.create();
googleGSON.toJson(comment);
JSONObject jObject = new JSONObject(googleGSON.toJson(comment));
JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.POST, url, jObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
submissionListener.onSuccess();
}
},
new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("submitComment", "(onErrorResponse) ERROR HAPPENED: " + error.toString());
submissionListener.onFailure();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
params.put("Authorization", userPreferences.getToken(context));
//params.put("Accept-Language", "fr");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(obreq);
}

There is nothing holding you back from using Retrofit. It works with Gson which you are already using and is very easy to use once you have set it up. You can also handle token based authentication with it.
For example this article will give you a great overview of Retrofit and will teach you how to use it.

Related

How do I add a custom authorization header to my JSON request?

I need to send a request that authorizes the user by providing a bearer token. How can i add a header to my request that contains this bearer token.
This is what my request looks like:
JsonObjectRequest jsonObjReq2 = new JsonObjectRequest(Request.Method.POST,
personUrl, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//something
}
});
You can override one more method, which is getHeaders().
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
params.put("Accept-Language", "en"); //add as many headers as you want
return params;
}
Little tip here is, stop using volley and use Retrofit Instead. Its much better, clean and easy.
You can check this course to learn retrofit in detail: Android Retrofit Tutorial.

Android Volley request failing

I am attempting a Volley request through android to get Oauth credentials using a password grant type. What I am trying works in postman, but is not working in android and I am not sure what I am doing wrong. Below please find the code I am using:
final RequestQueue queue = Volley.newRequestQueue(this);
final String url = Constants.OAUTH_URL;
Map<String, String> body = new HashMap<>();
body.put("grant", "password");
final JSONObject jso = new JSONObject(body);
JsonObjectRequest postRequest = new JsonObjectRequest (Request.Method.POST, url, jso,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(final JSONObject response) {
//Do something
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
responseText.setText(error.toString());
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("accept", "application/vnd.TestKitchen.v1+json");
headers.put("Authorization", BasicAuth.getBasicAuth(Constants.USERNAME, Constants.PASSWORD));
headers.put("Content-Type", "application/json; charset=UTF-8");
return headers;
}
};
queue.add(postRequest);
My OAuth URL is correct, I have verified that several times. So the problem isn't a typo on that end. All of the other fields should still reach my server and give an appropriate response (Be it an error or not), however all requests I send are returning with a 400 response. Anything obvious I am doing wrong that I should fix? Any help is appreciated. Thanks.
Why are you using this thing?
Map<String, String> body = new HashMap<>();
body.put("grant", "password");
final JSONObject jso = new JSONObject(body);
You can directly put the value in JSONObject
JSONObject jso = new JSONObject();
jso.put("grant", "password");
In the case of a REST API with a JSON payload, 400's are typically, and correctly I would say, used to indicate that the JSON is invalid in some way according to the API specification for the service.

How to send POST request in JSON and response in JSON using volley (Android)

private void login(){
// Post params to be sent to the server
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", username);
params.put("password", password);
JsonObjectRequest req = new JsonObjectRequest(login_URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.v("Response:%n %s", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
}){
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
// add the request object to the queue to be executed
AppController.getInstance().addToRequestQueue(req);}
I got below error:
E/Volley: [1] 10.onErrorResponse: Error:
i dont know where the problem
json send as post:
{
"":"",
"":"",
"":"",
}
json response as:
{"":""}
You should add the Request.Method.POST as the first parameter of your new JsonObjectRequest method. Also scrap out the new 'JSONObject(params)'.
Now override the getParams() method just above your getParams override and add the content of your login method there. You should return params.
It should work. Let me know if you have any challenges. :).
A very good example would be here
Volley library can be integrated using grader and if you want to know about implementation of Requests in volley then following link can give you all types of requests you can make with volley and how to implement it .
Here you go
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

Volley Post method gives me unexpected response code 400?

Here am new for android development am trying to post json value to server using gson lib i have converted into json but when i try to send to server is throws 400 unexpected response code here let me post my code:
listobj = account_sf_db.toServer();
Gson gson = new Gson();
RequestQueue queue = Volley.newRequestQueue(getBaseContext());
final String yog = gson.toJson(listobj);
String URL = "http://xxx.xx.xx.xxx/xxx/CRM/AcoountCreatePageLoad.svc/xxt/xxxt/ " +yog ;
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String resp = response.toString();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("god", yog);
return params;
} #Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Accept","application/json");
headers.put("User-agent", "My useragent");
return headers;
}
};
queue.add(stringRequest);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
400 status code is for Bad Request, it means server is not expecting this type of request.
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
Please check headers(content-type, user agent,etc.) you are adding whether it is required or not. It might happen that server is expecting a simple request and not json request.
Also try to read out error you get in onErrorResponse. Server might have responded you the expected parameter and request type, and also discuss the type of API developed by the web developer.
You have a space in your url after the /xxt/xxxt/
String URL = "http://xxx.xx.xx.xxx/xxx/CRM/AcoountCreatePageLoad.svc/xxt/xxxt/ " +yog ;
Remove it and I think you'll be fine.
P.S 400 generally means there is something wrong with the Url or parameters.

Post JsonObject with Volley

I'm trying to send a Post request with volley without success.
The lib is working correctly, and I manage to sent some string requests, but the Post with a JsonObject doesn't work.
String urlJsonReq = "https://api.parse.com/1/classes/GameScore";
String tag_json_obj = "tag_json";
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.POST,
urlJsonReq,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("MyApp", response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("MyApp", "Error: " + error.getMessage());
// hide the progress dialog
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("value1", "testValue1");
params.put("value2", "testValue2");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("X-Parse-REST-API-Key", "xxxxxxxxxxxx");
headers.put("X-Parse-Application-Id", "xxxxxxxxxxx");
return headers;
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
I keep getting an error. I read somewhere, but without any details that the volley cannot sent JsonObjects, only receive then. That if you want to solve that problem you should implement an custom class, but I really don't know if I'm just making an stupid mistake here (it is possible).
Do you guys know something about that?
Thank you for your time.
You can send the JSONObject without overiding the getParams or getBodyContentType. Something like this for example
JSONObject object = new JSONObject();
JsonObjectRequest jr = new JsonObjectRequest(Request.Method.POST, url, object, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Obviously you can Override the headers if you need to.

Categories

Resources