Java Examples for org.apache.http.client.RedirectStrategy
The following java examples will help you to understand the usage of org.apache.http.client.RedirectStrategy. These source code samples are taken from different open source projects.
Example 1
| Project: carrot2-master File: HttpUtils.java View source code |
/**
* Opens a HTTP/1.1 connection to the given URL using the GET method, decompresses
* compressed response streams, if supported by the server.
*
* @param url The URL to open. The URL must be properly escaped, this method will
* <b>not</b> perform any escaping.
* @param params Query string parameters to be attached to the url.
* @param headers Any extra HTTP headers to add to the request.
* @param user if not <code>null</code>, the user name to send during Basic
* Authentication
* @param password if not <code>null</code>, the password name to send during Basic
* Authentication
* @return The {@link HttpUtils.Response} object. Note that entire payload is read and
* buffered so that the HTTP connection can be closed when leaving this
* method.
*/
public static Response doGET(String url, Collection<NameValuePair> params, Collection<Header> headers, String user, String password, int timeoutMillis, RedirectStrategy redirectStrategy) throws IOException {
final DefaultHttpClient client = HttpClientFactory.getTimeoutingClient(timeoutMillis);
client.setRedirectStrategy(redirectStrategy);
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
final HttpGet request = new HttpGet();
final BasicHttpContext context = new BasicHttpContext();
final Response response = new Response();
try {
if (params == null)
params = Lists.newArrayList();
else
params = Lists.newArrayList(params);
URI uri = new URI(url);
params.addAll(URLEncodedUtils.parse(uri, "UTF-8"));
uri = URIUtils.createURI(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath(), URLEncodedUtils.format(Lists.newArrayList(params), "UTF-8"), null);
request.setURI(uri);
request.setHeader(HttpHeaders.URL_ENCODED);
request.setHeader(HttpHeaders.GZIP_ENCODING);
if (headers != null) {
for (Header header : headers) request.setHeader(header);
}
if (user != null && password != null) {
client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
// Use preemptive authentication (send credentials immediately to the target
// URI, without waiting for 401).
AuthCache authCache = new BasicAuthCache();
authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), new BasicScheme());
context.setAttribute(ClientContext.AUTH_CACHE, authCache);
}
logger.debug("GET: " + request.getURI());
final HttpResponse httpResponse = client.execute(request, context);
response.status = httpResponse.getStatusLine().getStatusCode();
response.statusMessage = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
InputStream stream = entity.getContent();
final Header encoded = entity.getContentEncoding();
if (encoded != null && "gzip".equalsIgnoreCase(encoded.getValue())) {
stream = new GZIPInputStream(stream);
response.compression = COMPRESSION_GZIP;
} else {
response.compression = COMPRESSION_NONE;
}
final Header[] respHeaders = httpResponse.getAllHeaders();
response.headers = new String[respHeaders.length][];
for (int i = 0; i < respHeaders.length; i++) {
response.headers[i] = new String[] { respHeaders[i].getName(), respHeaders[i].getValue() };
}
response.payload = StreamUtils.readFullyAndClose(stream);
return response;
} catch (URISyntaxException e) {
throw new IOException(e);
} finally {
client.getConnectionManager().shutdown();
}
}Example 2
| Project: rewrite-master File: SchemeChangeTest.java View source code |
@Test
public void testRedirectToHttps() {
DefaultHttpClient client = new DefaultHttpClient();
client.setRedirectStrategy(new RedirectStrategy() {
@Override
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
if (response.getFirstHeader("Location").getValue().contains("https"))
throw new RuntimeException("Success!");
return false;
}
@Override
public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
throw new IllegalStateException("Not implemented.");
}
});
try {
get(client, "/login");
} catch (Exception e) {
if (!"Success!".equals(e.getMessage()))
Assert.fail();
}
}Example 3
| Project: basic-algorithm-operations-master File: BrowserClient.java View source code |
protected void init() {
//Parameters
HttpParams params = getParams();
//Set Agent
HttpProtocolParams.setUserAgent(params, AGENT_IE8);
HttpClientParams.setCookiePolicy(params, CookiePolicy.BROWSER_COMPATIBILITY);
//Set redirect strategy
RedirectStrategy redirectStrategy = new PostRedirectStrategy();
setRedirectStrategy(redirectStrategy);
MiscParams.setRedirectStrategy(params, redirectStrategy);
//Interceptors
addRequestInterceptor(new RequestReferer());
addRequestInterceptor(new RequestResetRedirectChain());
}Example 4
| Project: pair-java-master File: HttpAgent.java View source code |
public HttpAgentResponse getResponse(String protocol, String basicAuthUsername, String basicAuthPassword, String host, int port, String path, Map<String, String> params, Boolean retry) throws URISyntaxException, IOException {
HttpClient httpclient = null;
RedirectStrategy redirect = new urlRedirectCapture();
HttpClientBuilder httpBuilder = HttpClientBuilder.create().setRedirectStrategy(redirect);
if (!retry) {
httpBuilder.disableAutomaticRetries();
}
httpclient = httpBuilder.build();
host = host.replaceFirst("(^http://|^https://)", "");
URIBuilder builder = new URIBuilder().setScheme(protocol).setHost(host);
if (path != null) {
builder.setPath(path);
}
if (!Strings.isNullOrEmpty(basicAuthPassword) && !Strings.isNullOrEmpty(basicAuthPassword)) {
builder.setUserInfo(basicAuthUsername, basicAuthPassword);
}
if (port > 0) {
builder.setPort(port);
}
if (params != null) {
for (Map.Entry<String, String> e : params.entrySet()) {
String val = URLDecoder.decode(e.getValue(), "UTF-8");
builder.setParameter(e.getKey(), val);
}
}
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
HttpContext context = new BasicHttpContext();
try {
httpget.setHeader("User-Agent", USER_AGENT);
HttpResponse response = httpclient.execute(httpget);
HttpEntity httpEntity = response.getEntity();
Header contentEncodingHeader = httpEntity.getContentEncoding();
String encoding;
if (contentEncodingHeader != null) {
encoding = contentEncodingHeader.getValue();
} else {
encoding = "UTF-8";
}
String responseEntity = EntityUtils.toString(httpEntity, encoding);
String resultUrl = httpget.getURI().toString();
String redirectUrl = (String) context.getAttribute("redirectUrl");
if (redirectUrl != null) {
resultUrl = redirectUrl;
}
return makeResponse(responseEntity, resultUrl);
} catch (HttpResponseException e) {
throw new IllegalArgumentException("URL Fetch failed: ", e);
}
}Example 5
| Project: Repository-master File: NexusRedirectStrategyTest.java View source code |
@Test
public void doNotFollowRedirectsToDirIndex() throws Exception {
when(response.getStatusLine()).thenReturn(statusLine);
final RedirectStrategy underTest = new NexusRedirectStrategy();
HttpContext httpContext;
// no location header
request = new HttpGet("http://localhost/dir/fileA");
httpContext = new BasicHttpContext();
httpContext.setAttribute(CONTENT_RETRIEVAL_MARKER_KEY, Boolean.TRUE);
when(statusLine.getStatusCode()).thenReturn(SC_OK);
assertThat(underTest.isRedirected(request, response, httpContext), is(false));
// redirect to file
request = new HttpGet("http://localhost/dir/fileA");
httpContext = new BasicHttpContext();
httpContext.setAttribute(CONTENT_RETRIEVAL_MARKER_KEY, Boolean.TRUE);
when(statusLine.getStatusCode()).thenReturn(SC_MOVED_TEMPORARILY);
when(response.getFirstHeader(argThat(equalToIgnoringCase(LOCATION)))).thenReturn(new BasicHeader(LOCATION, "http://localhost/dir/fileB"));
assertThat(underTest.isRedirected(request, response, httpContext), is(true));
// redirect to dir
request = new HttpGet("http://localhost/dir");
httpContext = new BasicHttpContext();
httpContext.setAttribute(CONTENT_RETRIEVAL_MARKER_KEY, Boolean.TRUE);
when(statusLine.getStatusCode()).thenReturn(SC_MOVED_TEMPORARILY);
when(response.getFirstHeader(argThat(equalToIgnoringCase(LOCATION)))).thenReturn(new BasicHeader(LOCATION, "http://localhost/dir/"));
assertThat(underTest.isRedirected(request, response, httpContext), is(false));
}Example 6
| Project: jw-community-master File: HttpUtil.java View source code |
/**
* Make a HTTP POST request to a URL, passing in a JSESSIONID cookie,
* with support for SSL (including prompting a warning for self-signed certs).
* If the JSESSIONID is invalid, then a password dialog appears.
* @param cookieStore
* @param url
* @param port
* @param sessionId
* @param cookieDomain
* @param cookiePath
* @param username
* @param password
* @param trustAllSsl
* @param failOnError
* @param filename
* @param file
* @return
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws KeyStoreException
* @throws UnrecoverableKeyException
* @throws AuthenticationException
*/
public static String httpPost(CookieStore cookieStore, String url, int port, String sessionId, String cookieDomain, String cookiePath, String username, String password, boolean trustAllSsl, boolean failOnError, String filename, File file) throws IOException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException, AuthenticationException {
String contents = null;
HttpClientBuilder httpClientBuilder = HttpClients.custom();
// Set no redirect
httpClientBuilder.setRedirectStrategy(new RedirectStrategy() {
@Override
public boolean isRedirected(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) {
return false;
}
@Override
public HttpUriRequest getRedirect(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) {
return null;
}
});
// set csrf token in URL
if (url.contains("?" + Designer.TOKEN_NAME)) {
url = url.substring(0, url.indexOf("?" + Designer.TOKEN_NAME));
}
url += "?" + Designer.TOKEN_NAME + "=" + URLEncoder.encode(Designer.TOKEN_VALUE, "UTF-8");
// Prepare a request object
HttpPost httpRequest = new HttpPost(url);
if (file != null) {
HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("packageXpdl", new FileBody(file)).build();
httpRequest.setEntity(reqEntity);
} else {
if (username != null && password != null) {
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("j_username", username));
formparams.add(new BasicNameValuePair("j_password", password));
formparams.add(new BasicNameValuePair("username", username));
formparams.add(new BasicNameValuePair("password", password));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
httpRequest.setEntity(entity);
}
}
// set referer header
String referer = "http://" + Designer.DOMAIN;
httpRequest.addHeader("Referer", referer);
// Set session cookie
if (cookieStore == null) {
cookieStore = new BasicCookieStore();
}
if (sessionId != null) {
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", sessionId);
cookie.setDomain(cookieDomain);
cookie.setPath(cookiePath);
cookieStore.addCookie(cookie);
}
httpClientBuilder.setDefaultCookieStore(cookieStore);
// Prepare SSL trust
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
if (SSL_TRUSTED || trustAllSsl) {
httpClientBuilder.setSSLSocketFactory(sslsf);
}
// Execute the request
CloseableHttpClient httpClient = httpClientBuilder.build();
try {
HttpResponse response = null;
try {
response = httpClient.execute(httpRequest);
} catch (SSLException se) {
int result = JOptionPane.showConfirmDialog(null, ResourceManager.getLanguageDependentString("InvalidSSLPrompt"), ResourceManager.getLanguageDependentString("InvalidSSLTitle"), JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
httpClientBuilder.setSSLSocketFactory(sslsf);
httpClient = httpClientBuilder.build();
response = httpClient.execute(httpRequest);
SSL_TRUSTED = true;
}
}
// Examine the response status
if (response == null) {
throw new HttpResponseException(403, ResourceManager.getLanguageDependentString("InvalidSSLMessage"));
}
StatusLine status = response.getStatusLine();
if (status == null || status.getStatusCode() == 302 || status.getStatusCode() == 401 || status.getStatusCode() == 500) {
if (failOnError) {
throw new AuthenticationException(ResourceManager.getLanguageDependentString("AuthenticationFailed"));
}
// Request is unauthenticated, attempt to authenticate
String credentials = password;
if (credentials == null) {
// prompt for username and password
JTextField uField = new JTextField(15);
uField.setText(username);
JPasswordField pField = new JPasswordField(15);
pField.addHierarchyListener(new HierarchyListener() {
public void hierarchyChanged(HierarchyEvent e) {
final Component c = e.getComponent();
if (c.isShowing() && (e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0) {
Window toplevel = SwingUtilities.getWindowAncestor(c);
toplevel.addWindowFocusListener(new WindowAdapter() {
@Override
public void windowGainedFocus(WindowEvent e) {
c.requestFocus();
}
});
}
}
});
JPanel pPanel = new JPanel(new GridLayout(2, 2));
pPanel.add(new JLabel(ResourceManager.getLanguageDependentString("UsernameKey")));
pPanel.add(uField);
pPanel.add(new JLabel(ResourceManager.getLanguageDependentString("PasswordKey")));
pPanel.add(pField);
int okCxl = JOptionPane.showConfirmDialog(null, pPanel, ResourceManager.getLanguageDependentString("SessionTimedOut"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (okCxl == JOptionPane.OK_OPTION) {
username = uField.getText();
credentials = new String(pField.getPassword());
Designer.USERNAME = username;
} else if (okCxl == JOptionPane.CANCEL_OPTION) {
return null;
}
}
try {
// login and store session cookie
String loginUrl = Designer.URLPATH + "/web/json/directory/user/sso";
String ssoResponse = HttpUtil.httpPost(cookieStore, loginUrl, port, null, cookieDomain, cookiePath, username, credentials, true, true, null, null);
String isAdminStr = "isAdmin";
if (!ssoResponse.contains(isAdminStr)) {
throw new AuthenticationException();
}
List<Cookie> cookies = cookieStore.getCookies();
for (Cookie ck : cookies) {
if ("JSESSIONID".equalsIgnoreCase(ck.getName())) {
sessionId = ck.getValue();
Designer.SESSION = sessionId;
}
}
// set new csrf token
String tokenAttr = "\"token\":\"";
if (ssoResponse.contains(tokenAttr)) {
String csrfToken = ssoResponse.substring(ssoResponse.indexOf(tokenAttr) + tokenAttr.length(), ssoResponse.length() - 2);
StringTokenizer st = new StringTokenizer(csrfToken, "=");
if (st.countTokens() == 2) {
Designer.TOKEN_NAME = st.nextToken();
Designer.TOKEN_VALUE = st.nextToken();
}
}
// repeat request with session cookie
contents = HttpUtil.httpPost(cookieStore, url, port, sessionId, cookieDomain, cookiePath, null, null, true, true, filename, file);
// return contents
return contents;
} catch (AuthenticationException ate) {
JOptionPane.showMessageDialog(null, ResourceManager.getLanguageDependentString("InvalidLogin"));
return HttpUtil.httpPost(null, url, port, sessionId, cookieDomain, cookiePath, username, null, false, false, filename, file);
} catch (HttpResponseException hre) {
throw new AuthenticationException(ResourceManager.getLanguageDependentString("InvalidLogin"));
}
}
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// to worry about connection release
if (entity != null) {
InputStream instream = null;
try {
instream = entity.getContent();
contents = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
String line = reader.readLine();
while (line != null) {
contents += line;
line = reader.readLine();
}
} catch (IOException ex) {
throw ex;
} catch (RuntimeException ex) {
httpRequest.abort();
throw ex;
} finally {
// Closing the input stream will trigger connection release
if (instream != null) {
instream.close();
}
}
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpClient.close();
}
return contents;
}Example 7
| Project: collector-http-master File: HttpCrawler.java View source code |
// Wraps redirection strategy to consider URLs as new documents to
// queue for processing.
private void initializeRedirectionStrategy() {
try {
Object chain = FieldUtils.readField(httpClient, "execChain", true);
Object redir = FieldUtils.readField(chain, "redirectStrategy", true);
if (redir instanceof RedirectStrategy) {
RedirectStrategy originalStrategy = (RedirectStrategy) redir;
RedirectStrategyWrapper strategyWrapper = new RedirectStrategyWrapper(originalStrategy, getCrawlerConfig().getRedirectURLProvider());
FieldUtils.writeField(chain, "redirectStrategy", strategyWrapper, true);
} else {
LOG.warn("Could not wrap RedirectStrategy to properly handle" + "redirects.");
}
} catch (Exception e) {
LOG.warn("\"maxConnectionInactiveTime\" could not be set since " + "internal connection manager does not support it.");
}
}Example 8
| Project: cxf-master File: AsyncHTTPConduitFactory.java View source code |
public synchronized void setupNIOClient(HTTPClientPolicy clientPolicy) throws IOReactorException {
if (client != null) {
return;
}
IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(ioThreadCount).setSelectInterval(selectInterval).setInterestOpQueued(interestOpQueued).setSoLinger(soLinger).setSoTimeout(soTimeout).setSoKeepAlive(soKeepalive).setTcpNoDelay(tcpNoDelay).build();
Registry<SchemeIOSessionStrategy> ioSessionFactoryRegistry = RegistryBuilder.<SchemeIOSessionStrategy>create().register("http", NoopIOSessionStrategy.INSTANCE).register("https", SSLIOSessionStrategy.getSystemDefaultStrategy()).build();
ManagedNHttpClientConnectionFactory connectionFactory = new ManagedNHttpClientConnectionFactory() {
@Override
public ManagedNHttpClientConnection create(final IOSession iosession, final ConnectionConfig config) {
ManagedNHttpClientConnection conn = super.create(iosession, config);
return conn;
}
};
DefaultConnectingIOReactor ioreactor = new DefaultConnectingIOReactor(config);
connectionManager = new PoolingNHttpClientConnectionManager(ioreactor, connectionFactory, ioSessionFactoryRegistry, DefaultSchemePortResolver.INSTANCE, SystemDefaultDnsResolver.INSTANCE, connectionTTL, TimeUnit.MILLISECONDS);
connectionManager.setDefaultMaxPerRoute(maxPerRoute);
connectionManager.setMaxTotal(maxConnections);
ConnectionConfig connectionConfig = ConnectionConfig.custom().setBufferSize(clientPolicy.getChunkLength() > 0 ? clientPolicy.getChunkLength() : 16332).build();
connectionManager.setDefaultConnectionConfig(connectionConfig);
RedirectStrategy redirectStrategy = new RedirectStrategy() {
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
return false;
}
public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
return null;
}
};
HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom().setConnectionManager(connectionManager).setRedirectStrategy(redirectStrategy).setDefaultCookieStore(new BasicCookieStore() {
private static final long serialVersionUID = 1L;
public void addCookie(Cookie cookie) {
}
});
adaptClientBuilder(httpAsyncClientBuilder);
client = httpAsyncClientBuilder.build();
// Start the client thread
client.start();
if (this.connectionTTL == 0) {
//if the connection does not have an expiry deadline
//use the ConnectionMaxIdle to close the idle connection
new CloseIdleConnectionThread(connectionManager, client).start();
}
}Example 9
| Project: jooby-master File: Client.java View source code |
public Client dontFollowRedirect() {
builder.setRedirectStrategy(new RedirectStrategy() {
@Override
public boolean isRedirected(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException {
return false;
}
@Override
public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException {
return null;
}
});
return this;
}Example 10
| Project: rhex-test-master File: RhexOmniAuthOIDCSecurityChecker.java View source code |
/**
*
* @param context
* @param userId
* @param userEmail
* @param userPassword
*
* @throws IllegalArgumentException if setup/configuration fails
*/
@Override
public void setUser(Context context, String userId, String userEmail, String userPassword) {
if (currentUser != null && currentUser.equals(userEmail)) {
// XXX
log.debug("same user context: no change");
// user is already active and context is set
return;
}
HttpContext httpContext = contexts.get(userEmail);
if (httpContext != null) {
//localContext = contexts.get(userEmail);
//if (localContext != null) {
log.debug("switch user context: {}", userEmail);
currentUser = userEmail;
localContext = httpContext;
// log.info("local user context: " + localContext.getAttribute("user"));
return;
}
log.info("set user context: " + userEmail);
final URI uri = context.getPropertyAsURI("loginURL");
if (uri == null) {
throw new IllegalArgumentException("loginURL property not defined");
}
/*
Step 1:
GET auth URL which redirects to authentication endpoint
GET -> http://rhex.mitre.org:3000/auth/openid_connect
Host: rhex.mitre.org:3000
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.3 (java 1.5)
redirects to http://rhex.mitre.org:3001/accounts/sign_in
*/
//HttpContext httpContext = localContext;
//if (httpContext == null) {
// Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
httpContext = new BasicHttpContext();
// Bind custom cookie store to the local context
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//}
HttpClient client = null;
URI redirect = null;
boolean debug = log.isDebugEnabled();
try {
client = context.getHttpClient();
if (client instanceof AbstractHttpClient) {
log.debug("*** set setRedirectStrategy ***");
AbstractHttpClient c = (AbstractHttpClient) client;
c.setRedirectStrategy(new RedirectStrategy() {
@Override
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
return false;
}
@Override
public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
return null;
}
});
}
log.debug("1.GET auth URL: {}", uri);
HttpGet req = new HttpGet(uri);
req.setHeader("Cache-Control", "no-cache");
// req.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
HttpResponse response = client.execute(req, httpContext);
// expect 302 response
// should redirect to something like:
// http://rhex.mitre.org:3001/authorizations/new?client_id=xx&nonce=xx&redirect_uri=http://rhex.mitre.org:3000/auth/openid_connect/callback&request=xxx&response_type=code&scope=openid
// getRedirectURI(response);
redirect = ClientHelper.getRedirectURI(response);
if (debug || redirect == null) {
ClientHelper.dumpResponse(req, response, true);
}
if (redirect == null) {
log.error("failed to get redirect URL");
return;
}
} catch (IOException e) {
log.error("", e);
return;
} finally {
if (client != null)
client.getConnectionManager().shutdown();
}
/*
* Step 2:
* Invoke GET on redirected URL at identity provider endpoint
* GET -> http://rhex.mitre.org:3001/authorizations/new?client_id=xx&nonce=xx&redirect_uri=http://rhex.mitre.org:3000/auth/openid_connect/callback&request=xxx&response_type=code&scope=openid
*/
String token = null;
// default FORM action for POST
String formAction = "/accounts/sign_in";
log.debug("*** 2.GET redirect URL: {}", redirect);
try {
client = context.getHttpClient();
//client = wrapClient(context.getHttpClient());
client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
HttpGet req = new HttpGet(redirect);
req.setHeader("Cache-Control", "no-cache");
HttpResponse response = client.execute(req, httpContext);
if (debug) {
ClientHelper.dumpResponse(req, response, false);
}
HttpEntity entity = response.getEntity();
if (entity != null)
try {
String text = EntityUtils.toString(entity);
// <form>...<input name="authenticity_token" type="hidden" value="LHrOI+YLyGQ9Y2vR9QS5wDaGze8j6/krFT6uHIz6f0o=" />
Pattern p = Pattern.compile("<input name=\"authenticity_token\".*?value=\"([^\"]+)");
Matcher m = p.matcher(text);
if (m.find()) {
token = m.group(1);
//System.out.println("\nXXX: ** MATCH ***" + token);
log.trace("Response body:\n{}", text);
} else {
// no match found
log.debug("Response body:\n{}", text);
}
// <form accept-charset="UTF-8" action="/accounts/sign_in" ...
p = Pattern.compile("<form\\s.*?action=\"([^\"]+)");
m = p.matcher(text);
if (m.find()) {
formAction = m.group(1);
//if (formAction.startsWith("/"))
//formAction = formAction.substring(1);
log.trace("form action={}", formAction);
}
} catch (IOException e) {
log.warn("", e);
}
else
log.warn("XXX: No body");
} catch (ParseException e) {
log.error("", e);
return;
} catch (IOException e) {
log.error("", e);
return;
} finally {
if (client != null)
client.getConnectionManager().shutdown();
}
if (token == null) {
log.error("failed to get auth token");
return;
}
/*
Step 3:
POST to form; e.g., http://rhex.mitre.org:3001/accounts/sign_in
action="/accounts/sign_in"
construct POST URL from auth endpoint and submit credentials
form parameters:
account[email] test@test.com
account[password] password
account[remember_me] 0
authenticity_token XsV2cW8kHyia6endlijMV37SeeiApdbmPXUi8UvsVJY=
commit Sign in
utf8 ?
utf8=%E2%9C%93&authenticity_token=XsV2cW8kHyia6endlijMV37SeeiApdbmPXUi8UvsVJY%3D&account%5Bemail%5D=test%40test.com&account%5Bpassword%5D=testtest&account%5Bremember_me%5D=0&commit=Sign+in
*/
final URI signInUrl = redirect.resolve(formAction);
/*
try {
final int port = redirect.getPort();
signInUrl = port == -1 ? new URI(String.format("%s://%s/%s",
redirect.getScheme(), redirect.getHost(), formAction))
: new URI(String.format("%s://%s:%d/%s",
redirect.getScheme(), redirect.getHost(), port, formAction));
} catch (URISyntaxException e) {
log.error("", e);
return;
}
*/
log.debug("*** 3.POST auth URL: {}", signInUrl);
HttpPost httppost = new HttpPost(signInUrl);
httppost.setHeader("Cache-Control", "no-cache");
List<NameValuePair> formParams = new ArrayList<NameValuePair>(5);
formParams.add(new BasicNameValuePair("account[email]", userEmail));
formParams.add(new BasicNameValuePair("account[password]", userPassword));
formParams.add(new BasicNameValuePair("authenticity_token", token));
formParams.add(new BasicNameValuePair("account[remember_me]", "0"));
formParams.add(new BasicNameValuePair("commit", "Sign in"));
// formParams.add(new BasicNameValuePair("utf8", "✓")); // %E2%9C%93
URI postRedirect = null;
try {
httppost.setEntity(new UrlEncodedFormEntity(formParams));
client = context.getHttpClient();
/*
if (client instanceof AbstractHttpClient) {
log.debug("*** setCredentials ***");
((AbstractHttpClient)client).getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
new UsernamePasswordCredentials("user", "pass"));
}
*/
HttpResponse response = client.execute(httppost, httpContext);
postRedirect = ClientHelper.getRedirectURI(response);
if (debug || postRedirect == null) {
ClientHelper.dumpResponse(httppost, response, true);
}
if (postRedirect == null) {
log.error("failed to get redirect URL");
return;
}
} catch (IOException e) {
throw new IllegalArgumentException(e);
} finally {
if (client != null)
client.getConnectionManager().shutdown();
}
/* Step 4:
*
* Expected POST Response: HTTP/1.1 302 Found
* Location: http://rhex.mitre.org:3001/authorizations/new?client_id=xxx&nonce=xxx&redirect_uri=http://rhex.mitre.org:3000/auth/openid_connect/callback&request=xxx&response_type=code&scope=openid
* GET redirect URL to verify authentication
*/
log.debug("*** 4.GET redirect URL: {}", postRedirect);
URI getRedirect = null;
try {
client = context.getHttpClient();
HttpGet req = new HttpGet(postRedirect);
req.setHeader("Cache-Control", "no-cache");
client.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);
HttpResponse response = client.execute(req, httpContext);
boolean success = response.getStatusLine().getStatusCode() == 302;
getRedirect = ClientHelper.getRedirectURI(response);
if (debug || !success) {
ClientHelper.dumpResponse(req, response, !success);
}
if (getRedirect == null) {
log.error("failed to get redirect URL");
return;
}
// boolean success = response.getStatusLine().getStatusCode() == 200;
// if HANDLE_REDIRECTS=false then
// Location: http://rhex-simple.mitre.org:3000/auth/openid_connect/callback?code=6415c21d14d45bf69054b9efca8b36591214c17490f643521cc7b0331f4386ec
} catch (IOException e) {
throw new IllegalArgumentException(e);
} finally {
if (client != null)
client.getConnectionManager().shutdown();
}
log.debug("*** 5.GET redirect URL: {}", getRedirect);
try {
client = context.getHttpClient();
HttpGet req = new HttpGet(getRedirect);
HttpResponse response = client.execute(req, httpContext);
boolean success = response.getStatusLine().getStatusCode() == 200;
if (debug || !success) {
System.out.println("XXX: 123-1");
ClientHelper.dumpResponse(req, response, !success);
System.out.println("XXX: 123-2");
}
if (success) {
log.info("XXX: authentication successful: {}", userEmail);
saveUriParameters(context, postRedirect, userId);
saveUriParameters(context, getRedirect, userId);
currentUser = userEmail;
this.localContext = httpContext;
// httpContext.setAttribute("user", userEmail);
// save context
contexts.put(userEmail, httpContext);
}
} catch (IOException e) {
throw new IllegalArgumentException(e);
} finally {
if (client != null)
client.getConnectionManager().shutdown();
}
}Example 11
| Project: spring-cloud-netflix-master File: SimpleHostRoutingFilter.java View source code |
protected CloseableHttpClient newClient() {
final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIMEOUT.get()).setConnectTimeout(CONNECTION_TIMEOUT.get()).setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
HttpClientBuilder httpClientBuilder = HttpClients.custom();
if (!this.sslHostnameValidationEnabled) {
httpClientBuilder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
}
return httpClientBuilder.setConnectionManager(newConnectionManager()).disableContentCompression().useSystemProperties().setDefaultRequestConfig(requestConfig).setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)).setRedirectStrategy(new RedirectStrategy() {
@Override
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
return false;
}
@Override
public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
return null;
}
}).build();
}Example 12
| Project: dropwizard-master File: HttpClientBuilderTest.java View source code |
@Test
public void usesACustomRedirectStrategy() throws Exception {
RedirectStrategy neverFollowRedirectStrategy = new RedirectStrategy() {
@Override
public boolean isRedirected(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws ProtocolException {
return false;
}
@Override
public HttpUriRequest getRedirect(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws ProtocolException {
return null;
}
};
ConfiguredCloseableHttpClient client = builder.using(neverFollowRedirectStrategy).createClient(apacheBuilder, connectionManager, "test");
assertThat(client).isNotNull();
assertThat(spyHttpClientBuilderField("redirectStrategy", apacheBuilder)).isSameAs(neverFollowRedirectStrategy);
}Example 13
| Project: uaa-master File: UaaContextFactory.java View source code |
public static ClientHttpRequestFactory getNoValidatingClientHttpRequestFactory(boolean followRedirects) {
ClientHttpRequestFactory requestFactory;
SSLContext sslContext;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (KeyManagementException e) {
throw new RuntimeException(e);
} catch (KeyStoreException e) {
throw new RuntimeException(e);
}
//
CloseableHttpClient httpClient = HttpClients.custom().setSslcontext(sslContext).setRedirectStrategy(followRedirects ? new DefaultRedirectStrategy() : new RedirectStrategy() {
@Override
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
return false;
}
@Override
public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
return null;
}
}).build();
requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
return requestFactory;
}Example 14
| Project: web-framework-master File: HttpClientBuilderTest.java View source code |
@Test
public void usesACustomRedirectStrategy() throws Exception {
RedirectStrategy neverFollowRedirectStrategy = new RedirectStrategy() {
@Override
public boolean isRedirected(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws ProtocolException {
return false;
}
@Override
public HttpUriRequest getRedirect(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws ProtocolException {
return null;
}
};
ConfiguredCloseableHttpClient client = builder.using(neverFollowRedirectStrategy).createClient(apacheBuilder, connectionManager, "test");
assertThat(client).isNotNull();
assertThat(spyHttpClientBuilderField("redirectStrategy", apacheBuilder)).isSameAs(neverFollowRedirectStrategy);
}Example 15
| Project: bugvm-master File: HttpClientBuilder.java View source code |
public CloseableHttpClient build() {
// Create main request executor
// We copy the instance fields to avoid changing them, and rename to avoid accidental use of the wrong version
PublicSuffixMatcher publicSuffixMatcherCopy = this.publicSuffixMatcher;
if (publicSuffixMatcherCopy == null) {
publicSuffixMatcherCopy = PublicSuffixMatcherLoader.getDefault();
}
HttpRequestExecutor requestExecCopy = this.requestExec;
if (requestExecCopy == null) {
requestExecCopy = new HttpRequestExecutor();
}
HttpClientConnectionManager connManagerCopy = this.connManager;
if (connManagerCopy == null) {
LayeredConnectionSocketFactory sslSocketFactoryCopy = this.sslSocketFactory;
if (sslSocketFactoryCopy == null) {
final String[] supportedProtocols = systemProperties ? split(System.getProperty("https.protocols")) : null;
final String[] supportedCipherSuites = systemProperties ? split(System.getProperty("https.cipherSuites")) : null;
HostnameVerifier hostnameVerifierCopy = this.hostnameVerifier;
if (hostnameVerifierCopy == null) {
hostnameVerifierCopy = new DefaultHostnameVerifier(publicSuffixMatcherCopy);
}
if (sslContext != null) {
sslSocketFactoryCopy = new SSLConnectionSocketFactory(sslContext, supportedProtocols, supportedCipherSuites, hostnameVerifierCopy);
} else {
if (systemProperties) {
sslSocketFactoryCopy = new SSLConnectionSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault(), supportedProtocols, supportedCipherSuites, hostnameVerifierCopy);
} else {
sslSocketFactoryCopy = new SSLConnectionSocketFactory(SSLContexts.createDefault(), hostnameVerifierCopy);
}
}
}
@SuppressWarnings("resource") final PoolingHttpClientConnectionManager poolingmgr = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactoryCopy).build(), null, null, dnsResolver, connTimeToLive, connTimeToLiveTimeUnit != null ? connTimeToLiveTimeUnit : TimeUnit.MILLISECONDS);
if (defaultSocketConfig != null) {
poolingmgr.setDefaultSocketConfig(defaultSocketConfig);
}
if (defaultConnectionConfig != null) {
poolingmgr.setDefaultConnectionConfig(defaultConnectionConfig);
}
if (systemProperties) {
String s = System.getProperty("http.keepAlive", "true");
if ("true".equalsIgnoreCase(s)) {
s = System.getProperty("http.maxConnections", "5");
final int max = Integer.parseInt(s);
poolingmgr.setDefaultMaxPerRoute(max);
poolingmgr.setMaxTotal(2 * max);
}
}
if (maxConnTotal > 0) {
poolingmgr.setMaxTotal(maxConnTotal);
}
if (maxConnPerRoute > 0) {
poolingmgr.setDefaultMaxPerRoute(maxConnPerRoute);
}
connManagerCopy = poolingmgr;
}
ConnectionReuseStrategy reuseStrategyCopy = this.reuseStrategy;
if (reuseStrategyCopy == null) {
if (systemProperties) {
final String s = System.getProperty("http.keepAlive", "true");
if ("true".equalsIgnoreCase(s)) {
reuseStrategyCopy = DefaultClientConnectionReuseStrategy.INSTANCE;
} else {
reuseStrategyCopy = NoConnectionReuseStrategy.INSTANCE;
}
} else {
reuseStrategyCopy = DefaultClientConnectionReuseStrategy.INSTANCE;
}
}
ConnectionKeepAliveStrategy keepAliveStrategyCopy = this.keepAliveStrategy;
if (keepAliveStrategyCopy == null) {
keepAliveStrategyCopy = DefaultConnectionKeepAliveStrategy.INSTANCE;
}
AuthenticationStrategy targetAuthStrategyCopy = this.targetAuthStrategy;
if (targetAuthStrategyCopy == null) {
targetAuthStrategyCopy = TargetAuthenticationStrategy.INSTANCE;
}
AuthenticationStrategy proxyAuthStrategyCopy = this.proxyAuthStrategy;
if (proxyAuthStrategyCopy == null) {
proxyAuthStrategyCopy = ProxyAuthenticationStrategy.INSTANCE;
}
UserTokenHandler userTokenHandlerCopy = this.userTokenHandler;
if (userTokenHandlerCopy == null) {
if (!connectionStateDisabled) {
userTokenHandlerCopy = DefaultUserTokenHandler.INSTANCE;
} else {
userTokenHandlerCopy = NoopUserTokenHandler.INSTANCE;
}
}
String userAgentCopy = this.userAgent;
if (userAgentCopy == null) {
if (systemProperties) {
userAgentCopy = System.getProperty("http.agent");
}
if (userAgentCopy == null) {
userAgentCopy = VersionInfo.getUserAgent("Apache-HttpClient", "org.apache.http.client", getClass());
}
}
ClientExecChain execChain = createMainExec(requestExecCopy, connManagerCopy, reuseStrategyCopy, keepAliveStrategyCopy, new ImmutableHttpProcessor(new RequestTargetHost(), new RequestUserAgent(userAgentCopy)), targetAuthStrategyCopy, proxyAuthStrategyCopy, userTokenHandlerCopy);
execChain = decorateMainExec(execChain);
HttpProcessor httpprocessorCopy = this.httpprocessor;
if (httpprocessorCopy == null) {
final HttpProcessorBuilder b = HttpProcessorBuilder.create();
if (requestFirst != null) {
for (final HttpRequestInterceptor i : requestFirst) {
b.addFirst(i);
}
}
if (responseFirst != null) {
for (final HttpResponseInterceptor i : responseFirst) {
b.addFirst(i);
}
}
b.addAll(new RequestDefaultHeaders(defaultHeaders), new RequestContent(), new RequestTargetHost(), new RequestClientConnControl(), new RequestUserAgent(userAgentCopy), new RequestExpectContinue());
if (!cookieManagementDisabled) {
b.add(new RequestAddCookies());
}
if (!contentCompressionDisabled) {
if (contentDecoderMap != null) {
final List<String> encodings = new ArrayList<String>(contentDecoderMap.keySet());
Collections.sort(encodings);
b.add(new RequestAcceptEncoding(encodings));
} else {
b.add(new RequestAcceptEncoding());
}
}
if (!authCachingDisabled) {
b.add(new RequestAuthCache());
}
if (!cookieManagementDisabled) {
b.add(new ResponseProcessCookies());
}
if (!contentCompressionDisabled) {
if (contentDecoderMap != null) {
final RegistryBuilder<InputStreamFactory> b2 = RegistryBuilder.create();
for (final Map.Entry<String, InputStreamFactory> entry : contentDecoderMap.entrySet()) {
b2.register(entry.getKey(), entry.getValue());
}
b.add(new ResponseContentEncoding(b2.build()));
} else {
b.add(new ResponseContentEncoding());
}
}
if (requestLast != null) {
for (final HttpRequestInterceptor i : requestLast) {
b.addLast(i);
}
}
if (responseLast != null) {
for (final HttpResponseInterceptor i : responseLast) {
b.addLast(i);
}
}
httpprocessorCopy = b.build();
}
execChain = new ProtocolExec(execChain, httpprocessorCopy);
execChain = decorateProtocolExec(execChain);
// Add request retry executor, if not disabled
if (!automaticRetriesDisabled) {
HttpRequestRetryHandler retryHandlerCopy = this.retryHandler;
if (retryHandlerCopy == null) {
retryHandlerCopy = DefaultHttpRequestRetryHandler.INSTANCE;
}
execChain = new RetryExec(execChain, retryHandlerCopy);
}
HttpRoutePlanner routePlannerCopy = this.routePlanner;
if (routePlannerCopy == null) {
SchemePortResolver schemePortResolverCopy = this.schemePortResolver;
if (schemePortResolverCopy == null) {
schemePortResolverCopy = DefaultSchemePortResolver.INSTANCE;
}
if (proxy != null) {
routePlannerCopy = new DefaultProxyRoutePlanner(proxy, schemePortResolverCopy);
} else if (systemProperties) {
routePlannerCopy = new SystemDefaultRoutePlanner(schemePortResolverCopy, ProxySelector.getDefault());
} else {
routePlannerCopy = new DefaultRoutePlanner(schemePortResolverCopy);
}
}
// Add redirect executor, if not disabled
if (!redirectHandlingDisabled) {
RedirectStrategy redirectStrategyCopy = this.redirectStrategy;
if (redirectStrategyCopy == null) {
redirectStrategyCopy = DefaultRedirectStrategy.INSTANCE;
}
execChain = new RedirectExec(execChain, routePlannerCopy, redirectStrategyCopy);
}
// Optionally, add service unavailable retry executor
final ServiceUnavailableRetryStrategy serviceUnavailStrategyCopy = this.serviceUnavailStrategy;
if (serviceUnavailStrategyCopy != null) {
execChain = new ServiceUnavailableRetryExec(execChain, serviceUnavailStrategyCopy);
}
// Optionally, add connection back-off executor
if (this.backoffManager != null && this.connectionBackoffStrategy != null) {
execChain = new BackoffStrategyExec(execChain, this.connectionBackoffStrategy, this.backoffManager);
}
Lookup<AuthSchemeProvider> authSchemeRegistryCopy = this.authSchemeRegistry;
if (authSchemeRegistryCopy == null) {
authSchemeRegistryCopy = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.BASIC, new BasicSchemeFactory()).register(AuthSchemes.DIGEST, new DigestSchemeFactory()).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()).register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build();
}
Lookup<CookieSpecProvider> cookieSpecRegistryCopy = this.cookieSpecRegistry;
if (cookieSpecRegistryCopy == null) {
cookieSpecRegistryCopy = CookieSpecRegistries.createDefault(publicSuffixMatcherCopy);
}
CookieStore defaultCookieStore = this.cookieStore;
if (defaultCookieStore == null) {
defaultCookieStore = new BasicCookieStore();
}
CredentialsProvider defaultCredentialsProvider = this.credentialsProvider;
if (defaultCredentialsProvider == null) {
if (systemProperties) {
defaultCredentialsProvider = new SystemDefaultCredentialsProvider();
} else {
defaultCredentialsProvider = new BasicCredentialsProvider();
}
}
List<Closeable> closeablesCopy = closeables != null ? new ArrayList<Closeable>(closeables) : null;
if (!this.connManagerShared) {
if (closeablesCopy == null) {
closeablesCopy = new ArrayList<Closeable>(1);
}
final HttpClientConnectionManager cm = connManagerCopy;
if (evictExpiredConnections || evictIdleConnections) {
final IdleConnectionEvictor connectionEvictor = new IdleConnectionEvictor(cm, maxIdleTime > 0 ? maxIdleTime : 10, maxIdleTimeUnit != null ? maxIdleTimeUnit : TimeUnit.SECONDS);
closeablesCopy.add(new Closeable() {
@Override
public void close() throws IOException {
connectionEvictor.shutdown();
}
});
connectionEvictor.start();
}
closeablesCopy.add(new Closeable() {
@Override
public void close() throws IOException {
cm.shutdown();
}
});
}
return new InternalHttpClient(execChain, connManagerCopy, routePlannerCopy, cookieSpecRegistryCopy, authSchemeRegistryCopy, defaultCookieStore, defaultCredentialsProvider, defaultRequestConfig != null ? defaultRequestConfig : RequestConfig.DEFAULT, closeablesCopy);
}Example 16
| Project: BigSemanticsJava-master File: RedirectHttpClient.java View source code |
@Override
protected RequestDirector createClientRequestDirector(HttpRequestExecutor requestExec, ClientConnectionManager conman, ConnectionReuseStrategy reustrat, ConnectionKeepAliveStrategy kastrat, HttpRoutePlanner rouplan, HttpProcessor httpProcessor, HttpRequestRetryHandler retryHandler, RedirectStrategy redirectStrategy, AuthenticationStrategy targetAuthStrategy, AuthenticationStrategy proxyAuthStrategy, UserTokenHandler userTokenHandler, HttpParams params) {
return new RedirectRequestDirector(log, requestExec, conman, reustrat, kastrat, rouplan, httpProcessor, retryHandler, redirectStrategy, targetAuthStrategy, proxyAuthStrategy, userTokenHandler, params);
}Example 17
| Project: comsat-master File: FiberHttpClientBuilder.java View source code |
public final FiberHttpClientBuilder setRedirectStrategy(RedirectStrategy redirectStrategy) {
builder.setRedirectStrategy(redirectStrategy);
return this;
}Example 18
| Project: Grendel-Scan-master File: CustomHttpClient.java View source code |
@Override
protected RequestDirector createClientRequestDirector(final HttpRequestExecutor requestExec, final ClientConnectionManager conman, final ConnectionReuseStrategy reustrat, final ConnectionKeepAliveStrategy kastrat, final HttpRoutePlanner rouplan, final HttpProcessor httpProcessor, final HttpRequestRetryHandler retryHandler, final RedirectStrategy redirectStrategy, final AuthenticationHandler targetAuthHandler, final AuthenticationHandler proxyAuthHandler, final UserTokenHandler stateHandler, final HttpParams params) {
return new CustomClientRequestDirector(requestExec, conman, reustrat, kastrat, rouplan, httpProcessor, proxyAuthHandler, stateHandler, params);
}Example 19
| Project: jspider-master File: HttpClientFactory.java View source code |
protected RedirectStrategy createRedirectStrategy() {
return new FormatLocationRedirectStrategy();
}Example 20
| Project: cas-master File: SimpleHttpClientFactoryBean.java View source code |
public RedirectStrategy getRedirectionStrategy() {
return this.redirectionStrategy;
}Example 21
| Project: dataservices-sdk-java-master File: SmartHttpClient.java View source code |
public void setRedirectStrategy(final RedirectStrategy strategy) {
delegateClient.setRedirectStrategy(strategy);
}Example 22
| Project: httpasyncclient-master File: AbstractHttpAsyncClient.java View source code |
public final synchronized RedirectStrategy getRedirectStrategy() {
if (this.redirectStrategy == null) {
this.redirectStrategy = new DefaultRedirectStrategy();
}
return this.redirectStrategy;
}Example 23
| Project: sling-master File: SlingClient.java View source code |
/**
* Assigns {@link RedirectStrategy} instance.
* <p>Please note this value can be overridden by the {@link #disableRedirectHandling()} method.</p>
*
* @param redirectStrategy custom redirect strategy
* @return this
*/
public final InternalBuilder<T> setRedirectStrategy(final RedirectStrategy redirectStrategy) {
httpClientBuilder.setRedirectStrategy(redirectStrategy);
return this;
}