Last active
September 22, 2015 06:25
-
-
Save jarryDk/10356968 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 java.io.IOException; | |
import java.util.ArrayList; | |
import java.util.Map; | |
import javax.ws.rs.client.Client; | |
import javax.ws.rs.client.ClientBuilder; | |
import javax.ws.rs.client.ClientRequestContext; | |
import javax.ws.rs.client.ClientRequestFilter; | |
import javax.ws.rs.client.Entity; | |
import javax.ws.rs.client.WebTarget; | |
import javax.ws.rs.core.Form; | |
import javax.ws.rs.core.NewCookie; | |
import javax.ws.rs.core.Response; | |
/** | |
* License : Apache License 2.0 | |
* | |
* The idea comes from : http://www.adam-bien.com/roller/abien/entry/client_side_http_basic_access | |
* | |
* @author Michael Bornholdt Nielsen [email protected] | |
* | |
*/ | |
public class FormAuthenticator implements ClientRequestFilter { | |
private ArrayList<Object> cookies; | |
public FormAuthenticator(String baseUri, String username, String password) { | |
cookies = new ArrayList<>(); | |
Client client = ClientBuilder.newClient(); | |
WebTarget baseTarget = client.target(baseUri); | |
Form form = new Form(); | |
form.param("j_username", username); | |
form.param("j_password", password); | |
Response response = baseTarget.path("j_security_check") | |
.request("application/x-www-form-urlencoded") | |
.post(Entity.form(form)); | |
Map<String, NewCookie> cr = response.getCookies(); | |
for (NewCookie cookie : cr.values()) { | |
cookies.add(cookie.toCookie()); | |
} | |
} | |
public void filter(ClientRequestContext requestContext) throws IOException { | |
if (cookies != null) { | |
requestContext.getHeaders().put("Cookie", cookies); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment