use of org.apache.http.client.CookieStore in project XobotOS by xamarin.
the class RequestAddCookies method process.
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
// Obtain cookie store
CookieStore cookieStore = (CookieStore) context.getAttribute(ClientContext.COOKIE_STORE);
if (cookieStore == null) {
this.log.info("Cookie store not available in HTTP context");
return;
}
// Obtain the registry of cookie specs
CookieSpecRegistry registry = (CookieSpecRegistry) context.getAttribute(ClientContext.COOKIESPEC_REGISTRY);
if (registry == null) {
this.log.info("CookieSpec registry not available in HTTP context");
return;
}
// Obtain the target host (required)
HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (targetHost == null) {
throw new IllegalStateException("Target host not specified in HTTP context");
}
// Obtain the client connection (required)
ManagedClientConnection conn = (ManagedClientConnection) context.getAttribute(ExecutionContext.HTTP_CONNECTION);
if (conn == null) {
throw new IllegalStateException("Client connection not specified in HTTP context");
}
String policy = HttpClientParams.getCookiePolicy(request.getParams());
if (this.log.isDebugEnabled()) {
this.log.debug("CookieSpec selected: " + policy);
}
URI requestURI;
if (request instanceof HttpUriRequest) {
requestURI = ((HttpUriRequest) request).getURI();
} else {
try {
requestURI = new URI(request.getRequestLine().getUri());
} catch (URISyntaxException ex) {
throw new ProtocolException("Invalid request URI: " + request.getRequestLine().getUri(), ex);
}
}
String hostName = targetHost.getHostName();
int port = targetHost.getPort();
if (port < 0) {
port = conn.getRemotePort();
}
CookieOrigin cookieOrigin = new CookieOrigin(hostName, port, requestURI.getPath(), conn.isSecure());
// Get an instance of the selected cookie policy
CookieSpec cookieSpec = registry.getCookieSpec(policy, request.getParams());
// Get all cookies available in the HTTP state
List<Cookie> cookies = new ArrayList<Cookie>(cookieStore.getCookies());
// Find cookies matching the given origin
List<Cookie> matchedCookies = new ArrayList<Cookie>();
for (Cookie cookie : cookies) {
if (cookieSpec.match(cookie, cookieOrigin)) {
if (this.log.isDebugEnabled()) {
this.log.debug("Cookie " + cookie + " match " + cookieOrigin);
}
matchedCookies.add(cookie);
}
}
// Generate Cookie request headers
if (!matchedCookies.isEmpty()) {
List<Header> headers = cookieSpec.formatCookies(matchedCookies);
for (Header header : headers) {
request.addHeader(header);
}
}
int ver = cookieSpec.getVersion();
if (ver > 0) {
boolean needVersionHeader = false;
for (Cookie cookie : matchedCookies) {
if (ver != cookie.getVersion()) {
needVersionHeader = true;
}
}
if (needVersionHeader) {
Header header = cookieSpec.getVersionHeader();
if (header != null) {
// Advertise cookie version support
request.addHeader(header);
}
}
}
// Stick the CookieSpec and CookieOrigin instances to the HTTP context
// so they could be obtained by the response interceptor
context.setAttribute(ClientContext.COOKIE_SPEC, cookieSpec);
context.setAttribute(ClientContext.COOKIE_ORIGIN, cookieOrigin);
}
use of org.apache.http.client.CookieStore in project oxAuth by GluuFederation.
the class TestSessionWorkflow method test.
@Parameters({ "userId", "userSecret", "clientId", "clientSecret", "redirectUri" })
@Test
public void test(final String userId, final String userSecret, final String clientId, final String clientSecret, final String redirectUri) throws Exception {
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
CookieStore cookieStore = new BasicCookieStore();
httpClient.setCookieStore(cookieStore);
ClientExecutor clientExecutor = new ApacheHttpClient4Executor(httpClient);
////////////////////////////////////////////////
// TV side. Code 1 //
////////////////////////////////////////////////
AuthorizationRequest authorizationRequest1 = new AuthorizationRequest(Arrays.asList(ResponseType.CODE), clientId, Arrays.asList("openid", "profile", "email"), redirectUri, null);
authorizationRequest1.setAuthUsername(userId);
authorizationRequest1.setAuthPassword(userSecret);
authorizationRequest1.getPrompts().add(Prompt.NONE);
authorizationRequest1.setState("af0ifjsldkj");
authorizationRequest1.setRequestSessionState(true);
AuthorizeClient authorizeClient1 = new AuthorizeClient(authorizationEndpoint);
authorizeClient1.setRequest(authorizationRequest1);
AuthorizationResponse authorizationResponse1 = authorizeClient1.exec(clientExecutor);
// showClient(authorizeClient1, cookieStore);
String code1 = authorizationResponse1.getCode();
String sessionState = authorizationResponse1.getSessionState();
Assert.assertNotNull("code1 is null", code1);
Assert.assertNotNull("sessionState is null", sessionState);
// TV sends the code to the Backend
// We don't use httpClient and cookieStore during this call
////////////////////////////////////////////////
// Backend 1 side. Code 1 //
////////////////////////////////////////////////
// Get the access token
TokenClient tokenClient1 = new TokenClient(tokenEndpoint);
TokenResponse tokenResponse1 = tokenClient1.execAuthorizationCode(code1, redirectUri, clientId, clientSecret);
String accessToken1 = tokenResponse1.getAccessToken();
Assert.assertNotNull("accessToken1 is null", accessToken1);
// Get the user's claims
UserInfoClient userInfoClient1 = new UserInfoClient(userInfoEndpoint);
UserInfoResponse userInfoResponse1 = userInfoClient1.execUserInfo(accessToken1);
Assert.assertTrue("userInfoResponse1.getStatus() is not 200", userInfoResponse1.getStatus() == 200);
// System.out.println(userInfoResponse1.getEntity());
////////////////////////////////////////////////
// TV side. Code 2 //
////////////////////////////////////////////////
AuthorizationRequest authorizationRequest2 = new AuthorizationRequest(Arrays.asList(ResponseType.CODE), clientId, Arrays.asList("openid", "profile", "email"), redirectUri, null);
authorizationRequest2.getPrompts().add(Prompt.NONE);
authorizationRequest2.setState("af0ifjsldkj");
authorizationRequest2.setSessionState(sessionState);
AuthorizeClient authorizeClient2 = new AuthorizeClient(authorizationEndpoint);
authorizeClient2.setRequest(authorizationRequest2);
AuthorizationResponse authorizationResponse2 = authorizeClient2.exec(clientExecutor);
// showClient(authorizeClient2, cookieStore);
String code2 = authorizationResponse2.getCode();
Assert.assertNotNull("code2 is null", code2);
// TV sends the code to the Backend
// We don't use httpClient and cookieStore during this call
////////////////////////////////////////////////
// Backend 2 side. Code 2 //
////////////////////////////////////////////////
// Get the access token
TokenClient tokenClient2 = new TokenClient(tokenEndpoint);
TokenResponse tokenResponse2 = tokenClient2.execAuthorizationCode(code2, redirectUri, clientId, clientSecret);
String accessToken2 = tokenResponse2.getAccessToken();
Assert.assertNotNull("accessToken2 is null", accessToken2);
// Get the user's claims
UserInfoClient userInfoClient2 = new UserInfoClient(userInfoEndpoint);
UserInfoResponse userInfoResponse2 = userInfoClient2.execUserInfo(accessToken2);
Assert.assertTrue("userInfoResponse1.getStatus() is not 200", userInfoResponse2.getStatus() == 200);
// System.out.println(userInfoResponse2.getEntity());
} finally {
if (httpClient != null) {
httpClient.getConnectionManager().shutdown();
}
}
}
use of org.apache.http.client.CookieStore in project platform_external_apache-http by android.
the class RequestAddCookies method process.
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
// Obtain cookie store
CookieStore cookieStore = (CookieStore) context.getAttribute(ClientContext.COOKIE_STORE);
if (cookieStore == null) {
this.log.info("Cookie store not available in HTTP context");
return;
}
// Obtain the registry of cookie specs
CookieSpecRegistry registry = (CookieSpecRegistry) context.getAttribute(ClientContext.COOKIESPEC_REGISTRY);
if (registry == null) {
this.log.info("CookieSpec registry not available in HTTP context");
return;
}
// Obtain the target host (required)
HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (targetHost == null) {
throw new IllegalStateException("Target host not specified in HTTP context");
}
// Obtain the client connection (required)
ManagedClientConnection conn = (ManagedClientConnection) context.getAttribute(ExecutionContext.HTTP_CONNECTION);
if (conn == null) {
throw new IllegalStateException("Client connection not specified in HTTP context");
}
String policy = HttpClientParams.getCookiePolicy(request.getParams());
if (this.log.isDebugEnabled()) {
this.log.debug("CookieSpec selected: " + policy);
}
URI requestURI;
if (request instanceof HttpUriRequest) {
requestURI = ((HttpUriRequest) request).getURI();
} else {
try {
requestURI = new URI(request.getRequestLine().getUri());
} catch (URISyntaxException ex) {
throw new ProtocolException("Invalid request URI: " + request.getRequestLine().getUri(), ex);
}
}
String hostName = targetHost.getHostName();
int port = targetHost.getPort();
if (port < 0) {
port = conn.getRemotePort();
}
CookieOrigin cookieOrigin = new CookieOrigin(hostName, port, requestURI.getPath(), conn.isSecure());
// Get an instance of the selected cookie policy
CookieSpec cookieSpec = registry.getCookieSpec(policy, request.getParams());
// Get all cookies available in the HTTP state
List<Cookie> cookies = new ArrayList<Cookie>(cookieStore.getCookies());
// Find cookies matching the given origin
List<Cookie> matchedCookies = new ArrayList<Cookie>();
for (Cookie cookie : cookies) {
if (cookieSpec.match(cookie, cookieOrigin)) {
if (this.log.isDebugEnabled()) {
this.log.debug("Cookie " + cookie + " match " + cookieOrigin);
}
matchedCookies.add(cookie);
}
}
// Generate Cookie request headers
if (!matchedCookies.isEmpty()) {
List<Header> headers = cookieSpec.formatCookies(matchedCookies);
for (Header header : headers) {
request.addHeader(header);
}
}
int ver = cookieSpec.getVersion();
if (ver > 0) {
boolean needVersionHeader = false;
for (Cookie cookie : matchedCookies) {
if (ver != cookie.getVersion()) {
needVersionHeader = true;
}
}
if (needVersionHeader) {
Header header = cookieSpec.getVersionHeader();
if (header != null) {
// Advertise cookie version support
request.addHeader(header);
}
}
}
// Stick the CookieSpec and CookieOrigin instances to the HTTP context
// so they could be obtained by the response interceptor
context.setAttribute(ClientContext.COOKIE_SPEC, cookieSpec);
context.setAttribute(ClientContext.COOKIE_ORIGIN, cookieOrigin);
}
use of org.apache.http.client.CookieStore in project platform_external_apache-http by android.
the class ResponseProcessCookies method process.
public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
if (response == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
// Obtain cookie store
CookieStore cookieStore = (CookieStore) context.getAttribute(ClientContext.COOKIE_STORE);
if (cookieStore == null) {
this.log.info("Cookie store not available in HTTP context");
return;
}
// Obtain actual CookieSpec instance
CookieSpec cookieSpec = (CookieSpec) context.getAttribute(ClientContext.COOKIE_SPEC);
if (cookieSpec == null) {
this.log.info("CookieSpec not available in HTTP context");
return;
}
// Obtain actual CookieOrigin instance
CookieOrigin cookieOrigin = (CookieOrigin) context.getAttribute(ClientContext.COOKIE_ORIGIN);
if (cookieOrigin == null) {
this.log.info("CookieOrigin not available in HTTP context");
return;
}
HeaderIterator it = response.headerIterator(SM.SET_COOKIE);
processCookies(it, cookieSpec, cookieOrigin, cookieStore);
// see if the cookie spec supports cookie versioning.
if (cookieSpec.getVersion() > 0) {
// process set-cookie2 headers.
// Cookie2 will replace equivalent Cookie instances
it = response.headerIterator(SM.SET_COOKIE2);
processCookies(it, cookieSpec, cookieOrigin, cookieStore);
}
}
use of org.apache.http.client.CookieStore in project local-data-aragopedia by aragonopendata.
the class Utils method processURLGetApache.
public static void processURLGetApache() {
CookieStore cookieStore = new BasicCookieStore();
RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
try {
HttpGet httpget = new HttpGet("http://bi.aragon.es/analytics/saw.dll?Go&path=/shared/IAEST-PUBLICA/Estadistica%20Local/03/030018TP&Action=Download&Options=df&NQUser=granpublico&NQPassword=granpublico");
httpget.addHeader("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36");
httpget.addHeader("Cookie", "sawU=granpublico; ORA_BIPS_LBINFO=153c4c924b8; ORA_BIPS_NQID=k8vgekohfuquhdg71on5hjvqbcorcupbmh4h3lu25iepaq5izOr07UFe9WiFvM3; __utma=263932892.849551431.1443517596.1457200753.1458759706.17; __utmc=263932892; __utmz=263932892.1456825145.15.6.utmcsr=alzir.dia.fi.upm.es|utmccn=(referral)|utmcmd=referral|utmcct=/kos/iaest/clase-vivienda-agregado");
httpget.addHeader("content-type", "text/csv; charset=utf-8");
RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).setConnectTimeout(5000).setConnectionRequestTimeout(5000).setCookieSpec(CookieSpecs.DEFAULT).build();
httpget.setConfig(requestConfig);
HttpClientContext context = HttpClientContext.create();
context.setCookieStore(cookieStore);
System.out.println("executing request " + httpget.getURI());
CloseableHttpResponse response = httpclient.execute(httpget, context);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("----------------------------------------");
context.getRequest();
context.getHttpRoute();
context.getTargetAuthState();
context.getTargetAuthState();
context.getCookieOrigin();
context.getCookieSpec();
context.getUserToken();
} finally {
response.close();
}
response = httpclient.execute(httpget, context);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("----------------------------------------");
context.getRequest();
context.getHttpRoute();
context.getTargetAuthState();
context.getTargetAuthState();
context.getCookieOrigin();
context.getCookieSpec();
context.getUserToken();
} finally {
response.close();
}
httpclient.close();
} catch (ClientProtocolException e) {
log.error("Error en el método processURLGetApache", e);
} catch (IOException e) {
log.error("Error en el método processURLGetApache", e);
}
}
Aggregations