Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve cookies in Retrofit?

I read about request interceptors and what not but no clue how to really use them to obtain cookies... I am sending the cookie like so from nodejs...

res.cookie('userid', user._id, { maxAge: 86400000, signed: true, path: '/' });

And in my android client - I have this set up so far for my RestApiManager

public class RestApiManager {
  private static final String API_URL = "ip: port";

    private static final RestAdapter REST_ADAPTER = new RestAdapter.Builder()
            .setEndpoint(API_URL)
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .build();

    //Call interface
    public interface AsynchronousApi {
  //Login User
        @FormUrlEncoded
        @POST("/login")
        public void loginUser(
                @Field("loginName") String loginName,
                @Field("password") String password,
                Callback<UserResponse> callback);
//Profile Picture
        @Multipart
        @POST("/profilePicture")
        public void uploadProfilePicture(
                @Part("photo") TypedFile photo,
                @Part("userId") String userId,
                Callback<UserResponse> callback); //success thumbnail to picasso

    }
    //create adapter
    private static final AsynchronousApi ASYNCHRONOUS_API = REST_ADAPTER.create(AsynchronousApi.class);

    //call service to initiate
    public static AsynchronousApi getAsyncApi() {
        return ASYNCHRONOUS_API;
    }
}

Separate cookie class:

    public class ApiCookie implements RequestInterceptor{
    // cookie use
    private String sessionId;

    public ApiCookie() {

    }

    //COOKIE BELOW
    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }

    public void clearSessionId() {
        sessionId = null;
    }


    @Override
    public void intercept(RequestFacade requestFacade) {
        setSessionId();
    }
}

trying to figure out how to obtain the cookie and be able to send it with future requests, so I do not need to include a userId field?

like image 733
Lion789 Avatar asked Mar 15 '14 15:03

Lion789


People also ask

How do I add cookies to retrofit?

How do I add cookies to retrofit? this cookies must be added: private HashMap<String, String> cookies = new HashMap(); cookies. put("sessionid", "sessionId"); cookies.

What is the difference between retrofit and retrofit2?

In Retrofit 1.9, if the fetched response couldn't be parsed into the defined Object, failure will be called. But in Retrofit 2.0, whether the response is be able to parse or not, onResponse will be always called. But in the case the result couldn't be parsed into the Object, response. body() will return as null.

What does an interceptor do in retrofit?

Interceptors, according to the documentation, are a powerful mechanism that can monitor, rewrite, and retry the API call. So, when we make an API call, we can either monitor it or perform some tasks. In a nutshell, Interceptors function similarly to airport security personnel during the security check process.

Is retrofit encrypted?

Retrofit Api Service The Retrofit saveUser service saves a Book object to the server. But the Encryption class is meant to intercept and convert the User object to an encrypted string.


1 Answers

I had similar situation in my app. This solution works for me to retrieve cookies using Retrofit. MyCookieManager.java

import java.io.IOException;
import java.net.CookieManager;
import java.net.URI;
import java.util.List;
import java.util.Map;

class MyCookieManager extends CookieManager {

    @Override
    public void put(URI uri, Map<String, List<String>> stringListMap) throws IOException {
        super.put(uri, stringListMap);
        if (stringListMap != null && stringListMap.get("Set-Cookie") != null)
            for (String string : stringListMap.get("Set-Cookie")) {
                if (string.contains("userid")) {
                    //save your cookie here
                }
            }
    }
}

Here is how to set your cookie for future requests using RequestInterceptor:

 MyCookieManager myCookieManager = new MyCookieManager();
            CookieHandler.setDefault(myCookieManager);
 private static final RestAdapter REST_ADAPTER = new RestAdapter.Builder()
            .setEndpoint(API_URL)
            .setLogLevel(RestAdapter.LogLevel.FULL)
                    .setRequestInterceptor(new RequestInterceptor() {
                        @Override
                        public void intercept(RequestFacade requestFacade) {
                            String userId = ;//get your saved userid here
                            if (userId != null)
                                requestFacade.addHeader("Cookie", userId);
                        }
                    })
            .build();
like image 165
Akhil Avatar answered Sep 30 '22 07:09

Akhil