Post With token_id and Json - android

Forgive me as I'm new to API driven development. I'm doing a front-end and back-end at the same time and ran into a snag.
On the back-end I accept URL encoded token_id that you may post to create a sessions. Goes like
http://someip:3000/sessions/create?token_id=sometoken
and works.
But now to create a post object the back-end expects a JSON object and a token_id. But reading some documentation for my front-end (android+retrofit) I understand that I can't URL encode a field (my token_id) and send a body as JSON.
Maybe I'm taking the wrong approach. Which path should I take to receive the token_id and a json object at the same time on the back-end?

I understand that I can't URL encode a field (my token_id) and send a
body as JSON.
This is true if you are trying to send POST parameters, because those are sent as the body. But you appear to be using query parameters which are part of the URL. You can use query parameters and JSON body in the same request. Your interface would be something like following, adjusting the body and return types for your particular case.
#POST("/sessions/create")
Call<Response> create(#Query("token_id") String tokenID, #Body MyBodyClass body);

Related

Decode a string encoded with Brotli returned by Android Volley

I'm sending an http request to a website using Volley (POST and StringRequest). The call is correctly executed. However, I can see that the result is a string codified. When seeing the headers of the answer I can see it is encoded in br, which means brotli. How can I decode the answer to later read it as a JSON?
Should I change to OkHttp or another alternative?

how to send retrofit request body from postman when request body is just json

I'm send data to rest service using retrofit and it works but when server crash and i need to test the api in postman but when using postman data is null,i can see that data are delivered using dump and die but when trying to access it return null
#POST("adToCart")
Call<CartDataResponse> addToCart(#Body CartData cartData);
As your request body is CartData, you can just simply use Gson.toJson(cartData) where, if you're using google Gson libray with retrofit and cartData is an object of CartData.java or the request model class. Print that value of the json which you have got from Gson.toJson(cartData), copy the json and put it into the body portion of postman and make sure that you have fill the hearder and correct endpoint, Then hit 'send' button which will give you your expected response. If not please share your steps for confirmation.

How to get a HEAD of a Retrofit call from an api endpoint that requires field in the request body?

I am trying to examine the headers of a response from an API call made via Retrofit 2.0.2 before actually downloading the content.
My API interface looks like the following:
#Headers({"Accept: application/json", "Origin: http://www.example.com"})
#HEAD("profiles")
Call<Void> getProfileHeaders(#Field("puids") String puid);
Please note that the API call requires me to specify in the body a field called puids=%{UUID} list of UUIDs in order to return a response.
If I would like to download the data without examining the headers first, I would just call an interface like this:
#Headers({"Accept: application/json", "Origin: http://www.example.com"})
#FormUrlEncoded
#POST("profiles")
Call<String> getProfile(#Field("puids") String puid);
Now the issue is that when I try to use the getProfileHeader() endpoint, I get the following RuntimeException:
java.lang.IllegalArgumentException: #Field parameters can only be used with form encoding. (parameter #1)
In order to use the #Field parameters (as I suppose a POST method would normally would do if required), I would have to explicitly specify that I use #FormUrlEncoded, but I can't make a #HEAD call with that.
I am a bit puzzled how could I achieve what I want and what am I missing?
Basically I would like to know how can I examine a retrofit call's response headers before downloading the actual body, of an API endpoint that requires field parameters?
Cheers!
Ok, I just realized that my confusion originates from a couple of misunderstandings:
#HEAD is an HTTP method to usually verify the hyperlinks validity and the server's response to a GET call. It does not work with POST request and it is theoretically incorrect.
Taken from RFC2616 of the HTTP/1.1 definitions:
The HEAD method is identical to GET except that the server MUST NOT
return a message-body in the response. The metainformation contained
in the HTTP headers in response to a HEAD request SHOULD be identical
to the information sent in response to a GET request. This method can
be used for obtaining metainformation about the entity implied by the
request without transferring the entity-body itself. This method is
often used for testing hypertext links for validity, accessibility,
and recent modification.
The response to a HEAD request MAY be cacheable in the sense that the
information contained in the response MAY be used to update a
previously cached entity from that resource. If the new field values
indicate that the cached entity differs from the current entity (as
would be indicated by a change in Content-Length, Content-MD5, ETag or
Last-Modified), then the cache MUST treat the cache entry as stale.
When making a POST request by definition we already calculated the response server-side and taken the time to download the body in consideration.
One of the function's of the POST method, as defined in RFC2616 is:
Providing a block of data, such as the result of submitting a form, to a data-handling process;
Hence verifying the header in order not do download the body beats the purpose of this.
As mentioned by #Radek above, using interceptors on GET request to modify and/or examine requests on the fly would do the work, but at that point we could also initiate a HEAD method request.
The solution to this problem would be to better align to the standard definitions defined in RFC2616 by making changes on the server-side to instead of returning block of raw data as a POST response, make it to return a resource that would be than called in a GET/HEAD request then. All just refactor the service call to use GET instead of POST.
Okhttp which is used by retrofit has Interceptors which let you modify or examine requests on the fly. Check out the github documentation

Android LoginActivity using standard http request

I'm using LoginActivity template and I'm trying to login to a website with email and password using a standard http request. The site doesn't provide an API so I'm thinking of somehow mirroring the site login to fill the email and password boxes on the page then sending the login request.
Think of logging in to stackoverflow for example by taking the input of an email and password TextView (s) and sending a standard http request to the authentication server with those credentials exactly how it would happen in the browser (same requests and addresses).
I haven't done anything like this before and I have no idea if it's even possible so please forgive any ignorance on my part.
This is done in Android in a similar fashion as in the web browser. Namely, you will send a POST request with proper parameters, let's say a JSON Object for the sake of explaining which contains something like:
{
username: 'myUsername'
password: 'mypass'
}
This will get processed and if your credentials are correct, you will get a response which may contain a variety of data, among which the accessToken (it may be called a slight variation of this).
You are supposed to remember this access token and use it to fetch any other data from the site, because that token is used from there on to authenticate you. I have an API I personally made, and I send the accessToken as a parameter in every request for a resource that is unavailable to the unregistered user.
As for the technical side, I'm using a nifty library called OkHttp for sending the Http requests, and it's quite rewarding and easy to use. Here's a code snippet to see what I'm talking about:
//JSON is a media type for parsing json
//json is a json string containing payload e.g. username and pass like in the example
OkHttpClient httpClient = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = httpClient.newCall(request).execute();
The only thing left to to for you is to properly parse the response. You can find various solutions on this topic, but I personally use 2 approaches, BufferedReader for huge responses using response.body().byteStream(), and plain old String for not-so-large responses using response.body().string().
This is not a short, but very thorough explanation, so feel free to ask for clarification if you do not get some part.
Assuming that you need to log in to sites like StackOverflow from your app with standard http request. That is simply impossible. Because no organizations will allow third party sites/apps handling their users' credentials. If they intend to share their resource with third party most organizations follow this procedure:
First they provide api for you to use.
With that api only you can make users to login i.e you can't handle those credentials
Then they give a token to you corresponding to the user.
With that token you can perform subsequent requests.
If the organization doesn't provide api then they most probably are in situation of not allowing third party sites/apps to access their users' resource.

Android Calling Django Server With POST Data

someone may asked my question already but I cannot find any suggestions.
I writing an Android app which needs to access my Django server by using HttpsURLConnection then Django server will return a JSON array to Android.
The view function in Django will receive the parameters from request.POST and generate the JSON array then return using HTTPResponse Django method. It does not need any Templates and Forms.
When I call the Django view function from Android, it returns 403 error. I know that it is because the POST data does not contains "csrf_token".
My problem is: How can I get the "csrf_token" and put it into my POST data before I send it to Django? I try disable the CSRF checking by "#csrf_exempt" it can return the correct result to Android app but I would not disable the CSRF checking.
Thanks,
Wilson
You have to send the cookies and also have to send a header 'X-CSRFToken' with csrftoken.
This is what I do (may not be the best way):
Get csrf token via a get request.But first try to see if you get a csrftoken cookie by doing same request on your browser with developer tools. If not, you should use ensure_csrf_cookie decorator
from django.views.decorators.csrf import ensure_csrf_cookie
#ensure_csrf_cookie
def your_view(request):
pass
Now using the same HttpUrlConnection object do this :
String cookieString="";
String csrftoken="";
// The below code can be shortened using for-each loop
List<HttpCookie> cookies=cookieManager.getCookieStore().getCookies();
Iterator<HttpCookie> cookieIterator=cookies.iterator();
while(cookieIterator.hasNext()){
HttpCookie cookie=cookieIterator.next();
cookieString+=cookie.getName()+"="+cookie.getValue()+";";
if(cookie.getName().equals("csrftoken")){
csrftoken=cookie.getValue();
}
}
Add the following to your post request:
urlConnection.setRequestProperty("X-CSRFToken", csrftoken);
urlConnection.setRequestProperty("Cookie", cookieString);

Categories

Resources