Last active
February 16, 2019 19:01
-
-
Save mageddo/7e44e89b43b2954808ba90db82836f40 to your computer and use it in GitHub Desktop.
CookieStore using JAX-RS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.apache.http.Header; | |
import org.apache.http.client.CookieStore; | |
import org.apache.http.impl.client.BasicCookieStore; | |
import org.apache.http.impl.cookie.BasicClientCookie; | |
import org.apache.http.impl.cookie.RFC6265StrictSpec; | |
import javax.ws.rs.client.ClientRequestContext; | |
import javax.ws.rs.client.ClientRequestFilter; | |
import javax.ws.rs.client.ClientResponseContext; | |
import javax.ws.rs.client.ClientResponseFilter; | |
import javax.ws.rs.core.Cookie; | |
import javax.ws.rs.core.NewCookie; | |
import java.io.IOException; | |
import java.util.List; | |
import java.util.Map; | |
public class AuthenticationFilter implements ClientResponseFilter, ClientRequestFilter { | |
private CookieStore cookieStore; | |
public EngooAuthenticationFilter() { | |
cookieStore = new BasicCookieStore(); | |
} | |
@Override | |
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { | |
for (final Map.Entry<String, NewCookie> entry : responseContext.getCookies().entrySet()) { | |
final var cookie = entry.getValue().toCookie(); | |
cookieStore.addCookie(new BasicClientCookie(cookie.getName(), cookie.getValue())); | |
} | |
} | |
@Override | |
public void filter(ClientRequestContext requestContext) throws IOException { | |
if(cookieStore.getCookies().isEmpty()){ | |
return; | |
} | |
final RFC6265StrictSpec spec = new RFC6265StrictSpec(); | |
for (final Header cookieHeader: spec.formatCookies(cookieStore.getCookies())) { | |
requestContext.getHeaders().add(cookieHeader.getName(), cookieHeader.getValue()); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Main { | |
public static void main(String[] args){ | |
newClient() | |
.target("https://mywebsite.com/api") | |
.register(AuthenticationFilter.class) | |
// .register(new AuthenticationFilter()) // or ... | |
; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment