下面列出了怎么用org.apache.http.protocol.HttpCoreContext的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void process(HttpResponse response, HttpContext context)
{
ManagedHttpClientConnection routedConnection = (ManagedHttpClientConnection) context
.getAttribute(HttpCoreContext.HTTP_CONNECTION);
// Connection may be stale, when no response body is returned
if (routedConnection.isOpen() && (response.getEntity() != null || !routedConnection.isStale()))
{
SSLSession sslSession = routedConnection.getSSLSession();
boolean secure = sslSession != null;
ConnectionDetails connectionDetails = new ConnectionDetails();
connectionDetails.setSecure(secure);
if (secure)
{
connectionDetails.setSecurityProtocol(sslSession.getProtocol());
}
httpTestContext.putConnectionDetails(connectionDetails);
}
}
@Test
void shouldSaveConnectionDetailsForSecuredConnectionAndDoNotCheckStalenessForResponsesWithEntity()
{
String protocol = "TLSv1.3";
SSLSession sslSession = mock(SSLSession.class);
when(sslSession.getProtocol()).thenReturn(protocol);
HttpContext context = mock(HttpContext.class);
ManagedHttpClientConnection connection = mock(ManagedHttpClientConnection.class);
when(context.getAttribute(HttpCoreContext.HTTP_CONNECTION)).thenReturn(connection);
when(connection.isOpen()).thenReturn(true);
when(connection.getSSLSession()).thenReturn(sslSession);
HttpResponse response = mock(HttpResponse.class);
when(response.getEntity()).thenReturn(mock(HttpEntity.class));
interceptor.process(response, context);
verify(httpTestContext).putConnectionDetails(argThat(connectionDetails -> connectionDetails.isSecure()
&& protocol.equals(connectionDetails.getSecurityProtocol())));
verify(connection, never()).isStale();
}
private void finishSpan(@Nullable Exception e) {
// start by reading the volatile field
final Span localSpan = span;
try {
if (context != null) {
Object responseObject = context.getAttribute(HttpCoreContext.HTTP_RESPONSE);
if (responseObject instanceof HttpResponse) {
StatusLine statusLine = ((HttpResponse) responseObject).getStatusLine();
if (statusLine != null) {
span.getContext().getHttp().withStatusCode(statusLine.getStatusCode());
}
}
}
localSpan.captureException(e);
} finally {
localSpan.end();
}
}
@Test
public void testSimpleSigner() throws Exception {
HttpEntityEnclosingRequest request =
new BasicHttpEntityEnclosingRequest("GET", "/query?a=b");
request.setEntity(new StringEntity("I'm an entity"));
request.addHeader("foo", "bar");
request.addHeader("content-length", "0");
HttpCoreContext context = new HttpCoreContext();
context.setTargetHost(HttpHost.create("localhost"));
createInterceptor().process(request, context);
assertEquals("bar", request.getFirstHeader("foo").getValue());
assertEquals("wuzzle", request.getFirstHeader("Signature").getValue());
assertNull(request.getFirstHeader("content-length"));
}
@Test
public void testEncodedUriSigner() throws Exception {
HttpEntityEnclosingRequest request =
new BasicHttpEntityEnclosingRequest("GET", "/foo-2017-02-25%2Cfoo-2017-02-26/_search?a=b");
request.setEntity(new StringEntity("I'm an entity"));
request.addHeader("foo", "bar");
request.addHeader("content-length", "0");
HttpCoreContext context = new HttpCoreContext();
context.setTargetHost(HttpHost.create("localhost"));
createInterceptor().process(request, context);
assertEquals("bar", request.getFirstHeader("foo").getValue());
assertEquals("wuzzle", request.getFirstHeader("Signature").getValue());
assertNull(request.getFirstHeader("content-length"));
assertEquals("/foo-2017-02-25%2Cfoo-2017-02-26/_search", request.getFirstHeader("resourcePath").getValue());
}
@Override
public boolean retryRequest(final IOException exception, final int executionCount, final HttpContext context) {
if(super.retryRequest(exception, executionCount, context)) {
final Object attribute = context.getAttribute(HttpCoreContext.HTTP_REQUEST);
if(attribute instanceof HttpUriRequest) {
final HttpUriRequest method = (HttpUriRequest) attribute;
log.warn(String.format("Retrying request %s", method));
try {
// Build the authorization string for the method.
authorizer.authorizeHttpRequest(method, context, null);
return true;
}
catch(ServiceException e) {
log.warn("Unable to generate updated authorization string for retried request", e);
}
}
}
return false;
}
@Test
public void process_response_closes_span_no_matter_what() {
// given
Span spanMock = mock(Span.class);
httpContext = spy(httpContext);
httpContext.setAttribute(SPAN_TO_CLOSE_HTTP_CONTEXT_ATTR_KEY, spanMock);
RuntimeException expectedEx = new RuntimeException("boom");
doThrow(expectedEx).when(httpContext).getAttribute(HttpCoreContext.HTTP_REQUEST);
// when
Throwable ex = catchThrowable(() -> interceptor.process(responseMock, httpContext));
// then
assertThat(ex).isSameAs(expectedEx);
verify(httpContext).getAttribute(HttpCoreContext.HTTP_REQUEST);
verify(spanMock).close();
}
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Decide about retry #" + executionCount + " for exception " + exception.getMessage());
}
if (executionCount >= _maxRetryCount) {
// Do not retry if over max retry count
return false;
} else if (exception instanceof NoHttpResponseException) {
// Retry if the server dropped connection on us
return true;
} else if (exception instanceof SSLHandshakeException) {
// Do not retry on SSL handshake exception
return false;
}
HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
// Retry if the request is considered idempotent
return idempotent;
}
@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);
// If no auth scheme available yet, try to initialize it preemptively
if (authState.getAuthScheme() == null) {
AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth");
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(HttpClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
if (authScheme != null) {
Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
if (creds == null) {
throw new HttpException("No credentials for preemptive authentication");
}
authState.update(authScheme, creds);
}
}
}
@Test
public void testProcess() throws Exception {
URI testURI = new URIBuilder()
.setPath("/1/statuses/update.json")
.setParameter("include_entities", "true")
.build();
HttpPost testRequest = new HttpPost(testURI);
testRequest.setEntity(new StringEntity("status="+security.encode("Hello Ladies + Gentlemen, a signed OAuth request!")));
HttpHost host = new HttpHost("api.twitter.com", -1, "https");
HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(testRequest, host);
TwitterOAuthConfiguration testOauthConfiguration = new TwitterOAuthConfiguration()
.withConsumerKey("xvz1evFS4wEEPTGEFPHBog")
.withConsumerSecret("kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw")
.withAccessToken("370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb")
.withAccessTokenSecret("LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE");
TwitterOAuthRequestInterceptor interceptor = Mockito.spy(new TwitterOAuthRequestInterceptor(testOauthConfiguration));
Mockito.when(interceptor.generateNonce()).thenReturn("kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg");
Mockito.when(interceptor.generateTimestamp()).thenReturn("1318622958");
interceptor.process(wrapper, new HttpCoreContext());
assertEquals(1, wrapper.getHeaders("Authorization").length);
String actual = wrapper.getFirstHeader("Authorization").getValue();
String expected = "OAuth oauth_consumer_key=\"xvz1evFS4wEEPTGEFPHBog\", oauth_nonce=\"kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg\", oauth_signature=\"tnnArxj06cWHq44gCs1OSKk%2FjLY%3D\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1318622958\", oauth_token=\"370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb\", oauth_version=\"1.0\"";
assertEquals(expected, actual);
}
private CookieStore getCorrectCookies(String uri) throws IOException {
CookieStore cookieStore = new BasicCookieStore();
HttpGet request = new HttpGet(uri);
try (CloseableHttpResponse response = sendRequest(request, new BasicCookieStore(), new HttpCoreContext())) {
for (org.apache.http.Header h: response.getHeaders("Set-Cookie")) {
if (h.getValue().contains(AuthenticationSessionManager.AUTH_SESSION_ID)) {
cookieStore.addCookie(parseCookie(h.getValue(), AuthenticationSessionManager.AUTH_SESSION_ID));
} else if (h.getValue().contains(KC_RESTART)) {
cookieStore.addCookie(parseCookie(h.getValue(), KC_RESTART));
}
}
}
return cookieStore;
}
private void login(String requestURI, CookieStore cookieStore) throws IOException {
HttpCoreContext httpContext = new HttpCoreContext();
HttpGet request = new HttpGet(requestURI);
// send an initial request, we are redirected to login page
String entityContent;
try (CloseableHttpResponse response = sendRequest(request, cookieStore, httpContext)) {
entityContent = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
}
// send credentials to login form
HttpPost post = new HttpPost(ActionURIUtils.getActionURIFromPageSource(entityContent));
List<NameValuePair> params = new LinkedList<>();
params.add(new BasicNameValuePair("username", "foo"));
params.add(new BasicNameValuePair("password", "password"));
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setEntity(new UrlEncodedFormEntity(params));
try (CloseableHttpResponse response = sendRequest(post, cookieStore, httpContext)) {
Assert.assertThat("Expected successful login.", response.getStatusLine().getStatusCode(), is(equalTo(200)));
}
}
@Test
void shouldSaveNoConnectionDetailsIfConnectionClosed()
{
HttpContext context = mock(HttpContext.class);
ManagedHttpClientConnection connection = mock(ManagedHttpClientConnection.class);
when(connection.isOpen()).thenReturn(Boolean.FALSE);
when(context.getAttribute(HttpCoreContext.HTTP_CONNECTION)).thenReturn(connection);
intercept(context);
verifyNoInteractions(httpTestContext);
verify(connection, never()).isStale();
}
private static ManagedHttpClientConnection mockHttpConnection(Boolean stale, HttpContext context, Boolean closed)
{
ManagedHttpClientConnection connection = mock(ManagedHttpClientConnection.class);
when(connection.isStale()).thenReturn(stale);
when(context.getAttribute(HttpCoreContext.HTTP_CONNECTION)).thenReturn(connection);
when(connection.isOpen()).thenReturn(closed);
return connection;
}
private static String getSession() throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(TEST_SERVICE_BASE_URL);
HttpContext httpContext = new BasicHttpContext();
httpClient.execute(httpGet, httpContext);
HttpUriRequest currentReq = (HttpUriRequest) httpContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
return currentReq.getURI().getPath().split("/")[2];
}
@Override
public void process(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException {
final HttpCoreContext coreContext = HttpCoreContext.adapt(httpContext);
final HttpInetConnection conn = coreContext.getConnection(HttpInetConnection.class);
if (!conn.isOpen()) {
return;
}
final SSLSession sslSession;
if (conn instanceof ManagedHttpClientConnection) {
sslSession = ((ManagedHttpClientConnection) conn).getSSLSession();
} else if (conn instanceof ManagedNHttpClientConnection) {
sslSession = ((ManagedNHttpClientConnection) conn).getSSLSession();
} else {
throw new RuntimeException("Unexpected connection type was used, " + conn);
}
if (sslSession != null) {
final Certificate[] certChain = sslSession.getPeerCertificates();
if (certChain == null || certChain.length == 0) {
throw new SSLPeerUnverifiedException("No certificates found");
}
try {
final X509Certificate cert = CertificateUtils.convertAbstractX509Certificate(certChain[0]);
trustedPeerDn = cert.getSubjectDN().getName().trim();
} catch (final CertificateException e) {
final String msg = "Could not extract subject DN from SSL session peer certificate";
logger.warn(msg);
eventReporter.reportEvent(Severity.WARNING, EVENT_CATEGORY, msg);
throw new SSLPeerUnverifiedException(msg);
}
}
}
protected String getRealRefServiceUrl(String baseUrl) throws ClientProtocolException, IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(baseUrl);
HttpContext httpContext = new BasicHttpContext();
httpclient.execute(httpGet, httpContext);
HttpUriRequest currentReq = (HttpUriRequest)httpContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
HttpHost currentHost = (HttpHost)httpContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
return currentReq.getURI().isAbsolute() ? currentReq.getURI().toString() : (currentHost.toURI() + currentReq.getURI());
}
@Test
public void testRetryRequest() {
final S3HttpRequestRetryHandler h = new S3HttpRequestRetryHandler(new JetS3tRequestAuthorizer() {
@Override
public void authorizeHttpRequest(final HttpUriRequest httpUriRequest, final HttpContext httpContext, final String s) {
//
}
}, 1);
final HttpClientContext context = new HttpClientContext();
context.setAttribute(HttpCoreContext.HTTP_REQUEST, new HttpHead());
assertTrue(h.retryRequest(new SSLException(new SocketException("Broken pipe")), 1, context));
}
private int getRetryCount(HttpCoreContext _context) {
int retry = 1;
try {
retry = new Long(_context.getConnection().getMetrics().getRequestCount()).intValue();
} catch (Exception e) {
// DO nothing
}
return retry - 1;
}
public Stats(HttpCoreContext context, HttpRequestBase request, HttpResponse response, long startMillis, long endMillis, long startRequestMillis) {
this._httpRequest = request;
this._httpResponse = response;
this._startMillis = startMillis;
this._endMillis = endMillis;
this._context = context;
this._startRequestMillis = startRequestMillis;
}
@Override
public boolean keepAlive(HttpResponse response, HttpContext context) {
HttpCoreContext coreContext = HttpCoreContext.adapt(context);
String host = coreContext.getTargetHost().getHostName();
if (vips.contains(host)) {
return false;
}
return super.keepAlive(response, context);
}
private HttpResponseInterceptor getHttpResponseInterceptor() {
return new HttpResponseInterceptor() {
@Override
public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
ManagedHttpClientConnection routedConnection = (ManagedHttpClientConnection)context.getAttribute(HttpCoreContext.HTTP_CONNECTION);
SSLSession sslSession = routedConnection.getSSLSession();
if (sslSession != null) {
Certificate[] certificates = sslSession.getPeerCertificates();
context.setAttribute(PEER_CERTIFICATES, certificates);
}
}
};
}
private String getRealUrl(HttpContext httpContext){
Object target = httpContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
Object reqUri = httpContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
if (target==null||reqUri==null){
return null;
}
HttpHost t = (HttpHost) target;
HttpUriRequest r = (HttpUriRequest)reqUri;
return r.getURI().isAbsolute()?r.getURI().toString():t.toString()+r.getURI().toString();
}
/**
* 重试策略.
*/
private HttpRequestRetryHandler retryPolicy() {
return (IOException exception, int executionCount, HttpContext context) -> {
// Do not retry if over max retry count
if (executionCount >= MAX_RETRY) return false;
// Retry if the server dropped connection on us
if (exception instanceof NoHttpResponseException) return true;
// Do not retry on SSL handshake exception
if (exception instanceof SSLHandshakeException) return false;
HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
// Retry if the request is considered idempotent
return !(request instanceof HttpEntityEnclosingRequest);
};
}
protected HttpContext createContext(HttpResponse response) {
HttpContext localContext = new HttpCoreContext();
CookieStore store = response.getCookieStore();
if (store != null) {
localContext.setAttribute(HttpClientContext.COOKIE_STORE, store);
}
return localContext;
}
protected void storeHeadersSent(HttpResponse response, HttpContext context) {
if (context instanceof HttpCoreContext) {
Header[] headersSent = ((HttpCoreContext)context).getRequest().getAllHeaders();
for (Header header : headersSent) {
response.addRequestHeader(header.getName(), header.getValue());
}
}
}
@Override
public void process(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException {
final HttpCoreContext coreContext = HttpCoreContext.adapt(httpContext);
final HttpInetConnection conn = coreContext.getConnection(HttpInetConnection.class);
if (!conn.isOpen()) {
return;
}
final SSLSession sslSession;
if (conn instanceof ManagedHttpClientConnection) {
sslSession = ((ManagedHttpClientConnection) conn).getSSLSession();
} else if (conn instanceof ManagedNHttpClientConnection) {
sslSession = ((ManagedNHttpClientConnection) conn).getSSLSession();
} else {
throw new RuntimeException("Unexpected connection type was used, " + conn);
}
if (sslSession != null) {
final Certificate[] certChain = sslSession.getPeerCertificates();
if (certChain == null || certChain.length == 0) {
throw new SSLPeerUnverifiedException("No certificates found");
}
try {
final X509Certificate cert = CertificateUtils.convertAbstractX509Certificate(certChain[0]);
trustedPeerDn = cert.getSubjectDN().getName().trim();
} catch (final CertificateException e) {
final String msg = "Could not extract subject DN from SSL session peer certificate";
logger.warn(msg);
eventReporter.reportEvent(Severity.WARNING, EVENT_CATEGORY, msg);
throw new SSLPeerUnverifiedException(msg);
}
}
}
@Test
// @Ignore
// 5.1
public final void whenCustomizingKeepAliveStrategy_thenNoExceptions() throws ClientProtocolException, IOException {
final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(final HttpResponse myResponse, final HttpContext myContext) {
final HeaderElementIterator it = new BasicHeaderElementIterator(myResponse.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
final HeaderElement he = it.nextElement();
final String param = he.getName();
final String value = he.getValue();
if ((value != null) && param.equalsIgnoreCase("timeout")) {
return Long.parseLong(value) * 1000;
}
}
final HttpHost target = (HttpHost) myContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
if ("localhost".equalsIgnoreCase(target.getHostName())) {
return 10 * 1000;
} else {
return 5 * 1000;
}
}
};
client = HttpClients.custom().setKeepAliveStrategy(myStrategy).setConnectionManager(poolingConnManager).build();
client.execute(get1);
client.execute(get2);
}
private String getRealServiceUrl(String baseUrl) throws ClientProtocolException, IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(baseUrl);
HttpContext httpContext = new BasicHttpContext();
httpclient.execute(httpGet, httpContext);
HttpUriRequest currentReq = (HttpUriRequest) httpContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
HttpHost currentHost = (HttpHost) httpContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
String currentUrl = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString() : (currentHost.toURI() + currentReq.getURI());
return currentUrl;
}
@Test
public void clientCertTest() throws Exception {
try (MockIpdServer sslMockIdpServer = new MockIpdServer(TestJwk.Jwks.ALL, SocketUtils.findAvailableTcpPort(),
true) {
@Override
protected void handleDiscoverRequest(HttpRequest request, HttpResponse response, HttpContext context)
throws HttpException, IOException {
MockIpdServer.SSLTestHttpServerConnection connection = (MockIpdServer.SSLTestHttpServerConnection) ((HttpCoreContext) context)
.getConnection();
X509Certificate peerCert = (X509Certificate) connection.getPeerCertificates()[0];
try {
String sha256Fingerprint = Hashing.sha256().hashBytes(peerCert.getEncoded()).toString();
Assert.assertEquals("04b2b8baea7a0a893f0223d95b72081e9a1e154a0f9b1b4e75998085972b1b68",
sha256Fingerprint);
} catch (CertificateEncodingException e) {
throw new RuntimeException(e);
}
super.handleDiscoverRequest(request, response, context);
}
}) {
SSLContextBuilder sslContextBuilder = SSLContexts.custom();
KeyStore trustStore = KeyStore.getInstance("JKS");
InputStream trustStream = new FileInputStream(
FileHelper.getAbsoluteFilePathFromClassPath("jwt/truststore.jks").toFile());
trustStore.load(trustStream, "changeit".toCharArray());
KeyStore keyStore = KeyStore.getInstance("JKS");
InputStream keyStream = new FileInputStream(
FileHelper.getAbsoluteFilePathFromClassPath("jwt/spock-keystore.jks").toFile());
keyStore.load(keyStream, "changeit".toCharArray());
sslContextBuilder.loadTrustMaterial(trustStore, null);
sslContextBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray(), new PrivateKeyStrategy() {
@Override
public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
return "spock";
}
});
SettingsBasedSSLConfigurator.SSLConfig sslConfig = new SettingsBasedSSLConfigurator.SSLConfig(
sslContextBuilder.build(), new String[] { "TLSv1.2", "TLSv1.1" }, null, null, false, false, false,
trustStore, null, keyStore, null, null);
KeySetRetriever keySetRetriever = new KeySetRetriever(sslMockIdpServer.getDiscoverUri(), sslConfig, false);
keySetRetriever.get();
}
}