Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RETROFIT & AUTH COOKIE

I need to know how to add an authorization cookie header in retrofit. I have seen advice like using request intercepter etc. Below is what I am trying, but is this correct? First of all I already needed a RequestAdatper to get the session id the first time around. This can only be set by the builder of the request adapter. But I needed to make a request just to get the session id in the first place. Do I need two rest adapters one to get the sessionId and another one after I have obtained it. What I really need is a method on adapter to set the cookie after I get it but it does not appear to be such a method. This is getting awkward. How do I set authorization cookie in retrofit? I don't see this in FAQ or tutorials.

RequestInterceptor requestInterceptor = new RequestInterceptor()
{   
   @Override
   public void intercept(RequestFacade request) {
        request.addHeader("Set-Cookie", "sessionId="+sessionIdentifier);
   }
 };

RestAdapter.Builder().setServer(serverURL)..setRequestIntercepter(requestIntercepter).build();  

// but I don't have sessionId when this is first issued ???
like image 338
user3186731 Avatar asked Jan 20 '14 21:01

user3186731


People also ask

What is retrofit used for?

Retrofit is used to perform the following tasks: It manages the process of receiving, sending, and creating HTTP requests and responses. It alternates IP addresses if there is a connection to a web service failure. It caches responses to avoid sending duplicate requests.

Is retrofit a framework?

Retrofit is a type-safe REST client for Android, Java and Kotlin developed by Square. The library provides a powerful framework for authenticating and interacting with APIs and sending network requests with OkHttp. See this guide to understand how OkHttp works.

What is difference between retrofit and retrofit2?

In Retrofit 1.9, GsonConverter is included in the package and is automatically initiated upon RestAdapter creation. As a result, the json result from server would be automatically parsed to the defined Data Access Object (DAO). But in Retrofit 2.0, Converter is not included in the package anymore.

What is retrofit and its benefits?

Retrofit will save your development time, And also you can keep your code in developer friendly. Retrofit has given almost all the API's to make server call and to receive response. internally they also use GSON to do the parsing.

What is Retrofit 2?

Retrofit is type-safe REST client for Android and Java which aims to make it easier to consume RESTful web services. We’ll not go into the details of Retrofit 1.x versions and jump onto Retrofit 2 directly which has a lot of new features and a changed internal API compared to the previous versions.

What is @retrofit in okhttp?

Retrofit is the class through which your API interfaces are turned into callable objects. By default, Retrofit will give you sane defaults for your platform but it allows for customization. By default, Retrofit can only deserialize HTTP bodies into OkHttp's ResponseBody type and it can only accept its RequestBody type for @Body.

What is retrofitting and what are some examples?

Retrofitting is thus different from merely renovating, which may not involve any new technology at all. The factory has been retrofitted to meet the new safety regulations. We can retrofit your car with the new fuel system. Recent Examples on the Web The Sustenir Agriculture system is designed to retrofit into any building in Singapore and beyond.

What is energy retrofit?

Retrofitting refers to the addition of new technology or features to older systems. power plant retrofit, improving power plant efficiency / increasing output / reducing emissions. home energy retrofit, the improving of existing buildings with energy efficiency equipment.


2 Answers

Keep a reference to the interceptor and treat it as a singleton like you would be RestAdapter itself.

public class ApiHeaders implements RequestInterceptor {
  private String sessionId;

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

  public void clearSessionId() {
    sessionId = null;
  }

  @Override public void intercept(RequestFacade request) {
    if (sessionId != null) {
      request.setHeader(...);
    }
  }
}

Now, simply call setSessionId after your authentication call. All subsequent requests will include the header.

like image 125
Jake Wharton Avatar answered Oct 01 '22 17:10

Jake Wharton


You can get the cookies like this

 public 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("JSESSIONID")) {
                    Preference.getInstance().setSessionId(string);
                }
            }
    }
}

Use this to set the CookieHandler

 MyCookieManager myCookieManager = new MyCookieManager();
        CookieHandler.setDefault(myCookieManager);

and then use it like this in your request Interceptor

 String sessionId = preference.getSessionId();
                    if (sessionId != null)
                        requestFacade.addHeader(Cookie, sessionId);
like image 41
Chetna Avatar answered Oct 01 '22 18:10

Chetna