use of org.apache.http.protocol.BasicHttpContext in project wildfly by wildfly.
the class OidcBaseTest method loginToApp.
public static void loginToApp(String appName, String username, String password, int expectedStatusCode, String expectedText, boolean loginToKeycloak) throws Exception {
final URI requestUri = new URL("http", TestSuiteEnvironment.getHttpAddress(), TestSuiteEnvironment.getHttpPort(), "/" + appName + SimpleSecuredServlet.SERVLET_PATH).toURI();
CookieStore store = new BasicCookieStore();
HttpClient httpClient = TestHttpClientUtils.promiscuousCookieHttpClientBuilder().setDefaultCookieStore(store).setRedirectStrategy(new LaxRedirectStrategy()).build();
HttpGet getMethod = new HttpGet(requestUri);
HttpContext context = new BasicHttpContext();
HttpResponse response = httpClient.execute(getMethod, context);
try {
int statusCode = response.getStatusLine().getStatusCode();
if (loginToKeycloak) {
assertTrue("Expected code == OK but got " + statusCode + " for request=" + requestUri, statusCode == HttpURLConnection.HTTP_OK);
Form keycloakLoginForm = new Form(response);
HttpResponse afterLoginClickResponse = simulateClickingOnButton(httpClient, keycloakLoginForm, username, password, "Sign In");
afterLoginClickResponse.getEntity().getContent();
assertEquals(expectedStatusCode, afterLoginClickResponse.getStatusLine().getStatusCode());
if (expectedText != null) {
String responseString = new BasicResponseHandler().handleResponse(afterLoginClickResponse);
assertTrue(responseString.contains(expectedText));
}
} else {
assertTrue("Expected code == FORBIDDEN but got " + statusCode + " for request=" + requestUri, statusCode == HttpURLConnection.HTTP_FORBIDDEN);
}
} finally {
HttpClientUtils.closeQuietly(response);
}
}
use of org.apache.http.protocol.BasicHttpContext in project platform_external_apache-http by android.
the class DefaultHttpClient method createHttpContext.
@Override
protected HttpContext createHttpContext() {
HttpContext context = new BasicHttpContext();
context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, getAuthSchemes());
context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, getCookieSpecs());
context.setAttribute(ClientContext.COOKIE_STORE, getCookieStore());
context.setAttribute(ClientContext.CREDS_PROVIDER, getCredentialsProvider());
return context;
}
use of org.apache.http.protocol.BasicHttpContext in project jmeter by apache.
the class HTTPHC4Impl method sample.
@Override
protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) {
if (log.isDebugEnabled()) {
log.debug("Start : sample {} method {} followingRedirect {} depth {}", url, method, areFollowingRedirect, frameDepth);
}
JMeterVariables jMeterVariables = JMeterContextService.getContext().getVariables();
HTTPSampleResult res = createSampleResult(url, method);
CloseableHttpClient httpClient = null;
HttpRequestBase httpRequest = null;
HttpContext localContext = new BasicHttpContext();
HttpClientContext clientContext = HttpClientContext.adapt(localContext);
clientContext.setAttribute(CONTEXT_ATTRIBUTE_AUTH_MANAGER, getAuthManager());
HttpClientKey key = createHttpClientKey(url);
MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager> triple;
try {
triple = setupClient(key, jMeterVariables, clientContext);
httpClient = triple.getLeft();
URI uri = url.toURI();
httpRequest = createHttpRequest(uri, method, areFollowingRedirect);
// can throw IOException
setupRequest(url, httpRequest, res);
} catch (Exception e) {
res.sampleStart();
res.sampleEnd();
errorResult(e, res);
return res;
}
setupClientContextBeforeSample(jMeterVariables, localContext);
res.sampleStart();
final CacheManager cacheManager = getCacheManager();
if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method) && cacheManager.inCache(url, httpRequest.getAllHeaders())) {
return updateSampleResultForResourceInCache(res);
}
CloseableHttpResponse httpResponse = null;
try {
currentRequest = httpRequest;
handleMethod(method, res, httpRequest, localContext);
// store the SampleResult in LocalContext to compute connect time
localContext.setAttribute(CONTEXT_ATTRIBUTE_SAMPLER_RESULT, res);
// perform the sample
httpResponse = executeRequest(httpClient, httpRequest, localContext, url);
saveProxyAuth(triple, localContext);
if (log.isDebugEnabled()) {
log.debug("Headers in request before:{}", Arrays.asList(httpRequest.getAllHeaders()));
}
// Needs to be done after execute to pick up all the headers
final HttpRequest request = (HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
if (log.isDebugEnabled()) {
log.debug("Headers in request after:{}, in localContext#request:{}", Arrays.asList(httpRequest.getAllHeaders()), Arrays.asList(request.getAllHeaders()));
}
extractClientContextAfterSample(jMeterVariables, localContext);
// We've finished with the request, so we can add the LocalAddress to it for display
if (localAddress != null) {
request.addHeader(HEADER_LOCAL_ADDRESS, localAddress.toString());
}
res.setRequestHeaders(getAllHeadersExceptCookie(request));
Header contentType = httpResponse.getLastHeader(HTTPConstants.HEADER_CONTENT_TYPE);
if (contentType != null) {
String ct = contentType.getValue();
res.setContentType(ct);
res.setEncodingAndType(ct);
}
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
res.setResponseData(readResponse(res, entity.getContent(), entity.getContentLength()));
}
// Done with the sampling proper.
res.sampleEnd();
currentRequest = null;
// Now collect the results into the HTTPSampleResult:
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
res.setResponseCode(Integer.toString(statusCode));
res.setResponseMessage(statusLine.getReasonPhrase());
res.setSuccessful(isSuccessCode(statusCode));
res.setResponseHeaders(getResponseHeaders(httpResponse));
if (res.isRedirect()) {
final Header headerLocation = httpResponse.getLastHeader(HTTPConstants.HEADER_LOCATION);
if (headerLocation == null) {
// HTTP protocol violation, but avoids NPE
throw new IllegalArgumentException("Missing location header in redirect for " + httpRequest.getRequestLine());
}
String redirectLocation = headerLocation.getValue();
res.setRedirectLocation(redirectLocation);
}
// record some sizes to allow HTTPSampleResult.getBytes() with different options
long headerBytes = // condensed length (without \r)
(long) res.getResponseHeaders().length() + // Add \r for each header
(long) httpResponse.getAllHeaders().length + // Add \r for initial header
1L + // final \r\n before data
2L;
HttpConnectionMetrics metrics = (HttpConnectionMetrics) localContext.getAttribute(CONTEXT_ATTRIBUTE_METRICS);
long totalBytes = metrics.getReceivedBytesCount();
res.setHeadersSize((int) headerBytes);
res.setBodySize(totalBytes - headerBytes);
res.setSentBytes((Long) localContext.getAttribute(CONTEXT_ATTRIBUTE_SENT_BYTES));
if (log.isDebugEnabled()) {
long total = res.getHeadersSize() + res.getBodySizeAsLong();
log.debug("ResponseHeadersSize={} Content-Length={} Total={}", res.getHeadersSize(), res.getBodySizeAsLong(), total);
}
// If we redirected automatically, the URL may have changed
if (getAutoRedirects()) {
HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
HttpHost target = (HttpHost) localContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
URI redirectURI = req.getURI();
if (redirectURI.isAbsolute()) {
res.setURL(redirectURI.toURL());
} else {
res.setURL(new URL(new URL(target.toURI()), redirectURI.toString()));
}
}
// Store any cookies received in the cookie manager:
saveConnectionCookies(httpResponse, res.getURL(), getCookieManager());
// Save cache information
if (cacheManager != null) {
cacheManager.saveDetails(httpResponse, res);
}
// Follow redirects and download page resources if appropriate:
res = resultProcessing(areFollowingRedirect, frameDepth, res);
if (!isSuccessCode(statusCode)) {
EntityUtils.consumeQuietly(httpResponse.getEntity());
}
} catch (IOException e) {
log.debug("IOException", e);
if (res.getEndTime() == 0) {
res.sampleEnd();
}
// pick up headers if failed to execute the request
if (res.getRequestHeaders() != null) {
log.debug("Overwriting request old headers: {}", res.getRequestHeaders());
}
res.setRequestHeaders(getAllHeadersExceptCookie((HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST)));
errorResult(e, res);
return res;
} catch (RuntimeException e) {
log.debug("RuntimeException", e);
if (res.getEndTime() == 0) {
res.sampleEnd();
}
errorResult(e, res);
return res;
} finally {
JOrphanUtils.closeQuietly(httpResponse);
currentRequest = null;
JMeterContextService.getContext().getSamplerContext().remove(CONTEXT_ATTRIBUTE_PARENT_SAMPLE_CLIENT_STATE);
}
return res;
}
use of org.apache.http.protocol.BasicHttpContext in project FBReaderJ by geometer.
the class ZLNetworkManager method perform.
void perform(ZLNetworkRequest request, BearerAuthenticator authenticator, int socketTimeout, int connectionTimeout) throws ZLNetworkException {
boolean success = false;
DefaultHttpClient httpClient = null;
HttpEntity entity = null;
try {
final HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, CookieStore);
request.doBefore();
final HttpParams params = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(params, socketTimeout);
HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
httpClient = new DefaultHttpClient(params) {
protected AuthenticationHandler createTargetAuthenticationHandler() {
final AuthenticationHandler base = super.createTargetAuthenticationHandler();
return new AuthenticationHandler() {
public Map<String, Header> getChallenges(HttpResponse response, HttpContext context) throws MalformedChallengeException {
return base.getChallenges(response, context);
}
public boolean isAuthenticationRequested(HttpResponse response, HttpContext context) {
return base.isAuthenticationRequested(response, context);
}
public AuthScheme selectScheme(Map<String, Header> challenges, HttpResponse response, HttpContext context) throws AuthenticationException {
try {
return base.selectScheme(challenges, response, context);
} catch (AuthenticationException e) {
final Header bearerHeader = challenges.get("bearer");
if (bearerHeader != null) {
String realm = null;
for (HeaderElement elt : bearerHeader.getElements()) {
final String name = elt.getName();
if (name == null) {
continue;
}
if ("realm".equals(name) || name.endsWith(" realm")) {
realm = elt.getValue();
break;
}
}
throw new BearerAuthenticationException(realm, response.getEntity());
}
throw e;
}
}
};
}
};
final HttpRequestBase httpRequest;
if (request instanceof ZLNetworkRequest.Get) {
httpRequest = new HttpGet(request.URL);
} else if (request instanceof ZLNetworkRequest.PostWithBody) {
httpRequest = new HttpPost(request.URL);
((HttpPost) httpRequest).setEntity(new StringEntity(((ZLNetworkRequest.PostWithBody) request).Body, "utf-8"));
/*
httpConnection.setRequestProperty(
"Content-Length",
Integer.toString(request.Body.getBytes().length)
);
*/
} else if (request instanceof ZLNetworkRequest.PostWithMap) {
final Map<String, String> parameters = ((ZLNetworkRequest.PostWithMap) request).PostParameters;
httpRequest = new HttpPost(request.URL);
final List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(parameters.size());
for (Map.Entry<String, String> entry : parameters.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
((HttpPost) httpRequest).setEntity(new UrlEncodedFormEntity(list, "utf-8"));
} else if (request instanceof ZLNetworkRequest.FileUpload) {
final ZLNetworkRequest.FileUpload uploadRequest = (ZLNetworkRequest.FileUpload) request;
final File file = ((ZLNetworkRequest.FileUpload) request).File;
httpRequest = new HttpPost(request.URL);
final MultipartEntity data = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("utf-8"));
data.addPart("file", new FileBody(uploadRequest.File));
((HttpPost) httpRequest).setEntity(data);
} else {
throw new ZLNetworkException("Unknown request type");
}
httpRequest.setHeader("User-Agent", ZLNetworkUtil.getUserAgent());
if (!request.isQuiet()) {
httpRequest.setHeader("X-Accept-Auto-Login", "True");
}
httpRequest.setHeader("Accept-Encoding", "gzip");
httpRequest.setHeader("Accept-Language", ZLResource.getLanguage());
for (Map.Entry<String, String> header : request.Headers.entrySet()) {
httpRequest.setHeader(header.getKey(), header.getValue());
}
httpClient.setCredentialsProvider(new MyCredentialsProvider(httpRequest, request.isQuiet()));
final HttpResponse response = execute(httpClient, httpRequest, httpContext, authenticator);
entity = response.getEntity();
if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
final AuthState state = (AuthState) httpContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
if (state != null) {
final AuthScopeKey key = new AuthScopeKey(state.getAuthScope());
if (myCredentialsCreator.removeCredentials(key)) {
entity = null;
}
}
}
final int responseCode = response.getStatusLine().getStatusCode();
InputStream stream = null;
if (entity != null && (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_PARTIAL)) {
stream = entity.getContent();
}
if (stream != null) {
try {
final Header encoding = entity.getContentEncoding();
if (encoding != null && "gzip".equalsIgnoreCase(encoding.getValue())) {
stream = new GZIPInputStream(stream);
}
request.handleStream(stream, (int) entity.getContentLength());
} finally {
stream.close();
}
success = true;
} else {
if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
throw new ZLNetworkAuthenticationException();
} else {
throw new ZLNetworkException(response.getStatusLine().toString());
}
}
} catch (ZLNetworkException e) {
throw e;
} catch (IOException e) {
e.printStackTrace();
final String code;
if (e instanceof UnknownHostException) {
code = ZLNetworkException.ERROR_RESOLVE_HOST;
} else {
code = ZLNetworkException.ERROR_CONNECT_TO_HOST;
}
throw ZLNetworkException.forCode(code, ZLNetworkUtil.hostFromUrl(request.URL), e);
} catch (Exception e) {
e.printStackTrace();
throw new ZLNetworkException(e.getMessage(), e);
} finally {
request.doAfter(success);
if (httpClient != null) {
httpClient.getConnectionManager().shutdown();
}
if (entity != null) {
try {
entity.consumeContent();
} catch (IOException e) {
}
}
}
}
use of org.apache.http.protocol.BasicHttpContext in project ddf by codice.
the class LogoutMessageImpl method sendSamlLogoutRequest.
@Override
public String sendSamlLogoutRequest(LogoutWrapper request, String targetUri, boolean isSoap, @Nullable Cookie cookie) throws IOException, LogoutSecurityException {
XMLObject xmlObject = isSoap ? SamlProtocol.createSoapMessage((SignableSAMLObject) request.getMessage()) : (XMLObject) request;
Element requestElement = getElementFromSaml(new LogoutWrapperImpl(xmlObject));
String requestMessage = DOM2Writer.nodeToString(requestElement);
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost post = new HttpPost(targetUri);
post.addHeader("Cache-Control", "no-cache, no-store");
post.addHeader("Pragma", "no-cache");
post.addHeader("SOAPAction", SAML_SOAP_ACTION);
post.addHeader("Content-Type", "application/soap+xml");
post.setEntity(new StringEntity(requestMessage, "utf-8"));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
BasicHttpContext context = new BasicHttpContext();
if (cookie != null) {
BasicClientCookie basicClientCookie = new BasicClientCookie(cookie.getName(), cookie.getValue());
basicClientCookie.setDomain(cookie.getDomain());
basicClientCookie.setPath(cookie.getPath());
BasicCookieStore cookieStore = new BasicCookieStore();
cookieStore.addCookie(basicClientCookie);
context.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
}
return httpClient.execute(post, responseHandler, context);
}
}
Aggregations