本文整理汇总了Java中org.apache.http.protocol.HttpContext.setAttribute方法的典型用法代码示例。如果您正苦于以下问题:Java HttpContext.setAttribute方法的具体用法?Java HttpContext.setAttribute怎么用?Java HttpContext.setAttribute使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.http.protocol.HttpContext
的用法示例。
在下文中一共展示了HttpContext.setAttribute方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: execute
import org.apache.http.protocol.HttpContext; //导入方法依赖的package包/类
public HttpResponse execute(HttpRequest request) throws IOException, HttpException {
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProcessor processor = new ImmutableHttpProcessor(new RequestContent());
HttpRequestExecutor executor = new HttpRequestExecutor();
HttpContext context = new BasicHttpContext(null);
context.setAttribute(ExecutionContext.HTTP_CONNECTION, connection);
if (!connection.isOpen()) {
Socket socket = new Socket(address.getAddress(), address.getPort());
connection.bind(socket, params);
}
context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
request.setParams(params);
executor.preProcess(request, processor, context);
HttpResponse response = executor.execute(request, connection, context);
executor.postProcess(response, processor, context);
return response;
}
示例2: createHttpContext
import org.apache.http.protocol.HttpContext; //导入方法依赖的package包/类
protected HttpContext createHttpContext() {
HttpContext context = new BasicHttpContext();
context.setAttribute(
ClientContext.SCHEME_REGISTRY,
getConnectionManager().getSchemeRegistry());
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;
}
示例3: authSucceeded
import org.apache.http.protocol.HttpContext; //导入方法依赖的package包/类
public void authSucceeded(
final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) {
if (authhost == null) {
throw new IllegalArgumentException("Host may not be null");
}
if (authScheme == null) {
throw new IllegalArgumentException("Auth scheme may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
if (isCachable(authScheme)) {
AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE);
if (authCache == null) {
authCache = new BasicAuthCache();
context.setAttribute(ClientContext.AUTH_CACHE, authCache);
}
if (this.log.isDebugEnabled()) {
this.log.debug("Caching '" + authScheme.getSchemeName() +
"' auth scheme for " + authhost);
}
authCache.put(authhost, authScheme);
}
}
示例4: logsRequestAndResponseFields
import org.apache.http.protocol.HttpContext; //导入方法依赖的package包/类
@Test
public void logsRequestAndResponseFields() {
HttpContext context = new BasicHttpContext();
context.setAttribute(HTTP_TARGET_HOST, "http://www.google.com");
OutboundRequestLoggingInterceptor interceptor = new OutboundRequestLoggingInterceptor(new FakeClock(20));
interceptor.process(new BasicHttpRequest("GET", "/something"), context);
interceptor.process(new BasicHttpResponse(new BasicStatusLine(ANY_PROTOCOL, 200, "any")), context);
Map<String, Object> fields = new ConcurrentHashMap<>();
fields.put("requestMethod", "GET");
fields.put("requestURI", "http://www.google.com/something");
testAppender.assertEvent(0, INFO, "Outbound request start", appendEntries(fields));
fields.put("responseTime", 20L);
fields.put("responseCode", 200);
testAppender.assertEvent(1, INFO, "Outbound request finish", appendEntries(fields));
}
示例5: allowEmptyConstructorToBuildDefaultClock
import org.apache.http.protocol.HttpContext; //导入方法依赖的package包/类
@Test
public void allowEmptyConstructorToBuildDefaultClock() {
testAppender.clearEvents();
HttpContext context = new BasicHttpContext();
context.setAttribute(HTTP_TARGET_HOST, "http://www.google.com");
OutboundRequestLoggingInterceptor interceptor = new OutboundRequestLoggingInterceptor();
interceptor.process(new BasicHttpRequest("GET", "/something"), context);
interceptor.process(new BasicHttpResponse(new BasicStatusLine(ANY_PROTOCOL, 200, "any")), context);
assertThat(testAppender.getEvents()).extracting("message")
.contains("Outbound request start", Index.atIndex(0))
.contains("Outbound request finish", Index.atIndex(1));
}
示例6: connect
import org.apache.http.protocol.HttpContext; //导入方法依赖的package包/类
@Override
public void connect(final HttpClientConnection conn, final HttpRoute route,
final int connectTimeout, final HttpContext context) throws IOException {
try {
super.connect(conn, route, connectTimeout, context);
} catch (SSLProtocolException e) {
Boolean enableSniValue =
(Boolean) context.getAttribute(SniSSLConnectionSocketFactory.ENABLE_SNI);
boolean enableSni = enableSniValue == null || enableSniValue;
if (enableSni && e.getMessage() != null &&
e.getMessage().equals("handshake alert: unrecognized_name")) {
logger.warn("Server saw wrong SNI host, retrying without SNI");
context.setAttribute(SniSSLConnectionSocketFactory.ENABLE_SNI, false);
super.connect(conn, route, connectTimeout, context);
} else {
throw e;
}
}
}
示例7: testManualParentSpan
import org.apache.http.protocol.HttpContext; //导入方法依赖的package包/类
@Test
public void testManualParentSpan() throws IOException {
MockSpan parent = mockTracer.buildSpan("parent")
.startManual();
{
ActiveSpan parentSpan = mockTracer.buildSpan("parent")
.startActive();
HttpContext context = new BasicHttpContext();
context.setAttribute(Constants.PARENT_CONTEXT, parent.context());
CloseableHttpClient client = clientBuilder.build();
client.execute(new HttpGet(serverUrl("/echo/a")), context);
}
List<MockSpan> mockSpans = mockTracer.finishedSpans();
Assert.assertEquals(2, mockSpans.size());
Assert.assertEquals(parent.context().traceId(), mockSpans.get(1).context().traceId());
Assert.assertEquals(parent.context().spanId(), mockSpans.get(1).parentId());
assertLocalSpan(mockSpans.get(1));
}
开发者ID:opentracing-contrib,项目名称:java-apache-httpclient,代码行数:25,代码来源:TracingHttpClientBuilderTest.java
示例8: createHttpContext
import org.apache.http.protocol.HttpContext; //导入方法依赖的package包/类
protected HttpContext createHttpContext(HttpProxy httpProxy, CookieStore cookieStore) {
HttpContext httpContext = new HttpClientContext();
if (cookieStore != null) {
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
}
if (httpProxy != null && StringUtils.isNotBlank(httpProxy.getUsername())) {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(httpProxy.getHost(), httpProxy.getPort()),
new UsernamePasswordCredentials(httpProxy.getUsername(), httpProxy.getPassword()));
httpContext.setAttribute(HttpClientContext.CREDS_PROVIDER, credentialsProvider);
}
return httpContext;
}
示例9: process
import org.apache.http.protocol.HttpContext; //导入方法依赖的package包/类
public void process(HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException {
final HttpClientContext clientContext = HttpClientContext.adapt(httpContext);
List<Cookie> cookies = clientContext.getCookieStore().getCookies();
boolean set = (null != StickyCookieHolder.getTestStickySessionCookie());
boolean found = false;
ListIterator<Cookie> it = cookies.listIterator();
while (it.hasNext()) {
Cookie cookie = it.next();
if (cookie.getName().equals(StickyCookieHolder.COOKIE_NAME)) {
found = true;
if (set) {
// set the cookie with the value saved for each thread using the rule
it.set(StickyCookieHolder.getTestStickySessionCookie());
} else {
// if the cookie is not set in TestStickySessionRule, remove it from here
it.remove();
}
}
}
// if the cookie needs to be set from TestStickySessionRule but did not exist in the client cookie list, add it here.
if (!found && set) {
cookies.add(StickyCookieHolder.getTestStickySessionCookie());
}
BasicCookieStore cs = new BasicCookieStore();
cs.addCookies(cookies.toArray(new Cookie[cookies.size()]));
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cs);
}
示例10: createAsyncRequest
import org.apache.http.protocol.HttpContext; //导入方法依赖的package包/类
@Override
public AsyncClientHttpRequest createAsyncRequest(URI uri, HttpMethod httpMethod) throws IOException {
HttpAsyncClient asyncClient = getHttpAsyncClient();
startAsyncClient();
HttpUriRequest httpRequest = createHttpUriRequest(httpMethod, uri);
postProcessHttpRequest(httpRequest);
HttpContext context = createHttpContext(httpMethod, uri);
if (context == null) {
context = HttpClientContext.create();
}
// Request configuration not set in the context
if (context.getAttribute(HttpClientContext.REQUEST_CONFIG) == null) {
// Use request configuration given by the user, when available
RequestConfig config = null;
if (httpRequest instanceof Configurable) {
config = ((Configurable) httpRequest).getConfig();
}
if (config == null) {
config = RequestConfig.DEFAULT;
}
context.setAttribute(HttpClientContext.REQUEST_CONFIG, config);
}
return new HttpComponentsAsyncClientHttpRequest(asyncClient, httpRequest, context);
}
示例11: createRequest
import org.apache.http.protocol.HttpContext; //导入方法依赖的package包/类
@Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
CloseableHttpClient client = (CloseableHttpClient) getHttpClient();
Assert.state(client != null, "Synchronous execution requires an HttpClient to be set");
HttpUriRequest httpRequest = createHttpUriRequest(httpMethod, uri);
postProcessHttpRequest(httpRequest);
HttpContext context = createHttpContext(httpMethod, uri);
if (context == null) {
context = HttpClientContext.create();
}
// Request configuration not set in the context
if (context.getAttribute(HttpClientContext.REQUEST_CONFIG) == null) {
// Use request configuration given by the user, when available
RequestConfig config = null;
if (httpRequest instanceof Configurable) {
config = ((Configurable) httpRequest).getConfig();
}
if (config == null) {
if (this.socketTimeout > 0 || this.connectTimeout > 0) {
config = RequestConfig.custom()
.setConnectTimeout(this.connectTimeout)
.setSocketTimeout(this.socketTimeout)
.build();
}
else {
config = RequestConfig.DEFAULT;
}
}
context.setAttribute(HttpClientContext.REQUEST_CONFIG, config);
}
if (this.bufferRequestBody) {
return new HttpComponentsClientHttpRequest(client, httpRequest, context);
}
else {
return new HttpComponentsStreamingClientHttpRequest(client, httpRequest, context);
}
}
示例12: authSucceeded
import org.apache.http.protocol.HttpContext; //导入方法依赖的package包/类
public void authSucceeded(
final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) {
AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE);
if (isCachable(authScheme)) {
if (authCache == null) {
authCache = new BasicAuthCache();
context.setAttribute(ClientContext.AUTH_CACHE, authCache);
}
if (this.log.isDebugEnabled()) {
this.log.debug("Caching '" + authScheme.getSchemeName() +
"' auth scheme for " + authhost);
}
authCache.put(authhost, authScheme);
}
}
示例13: tryConnect
import org.apache.http.protocol.HttpContext; //导入方法依赖的package包/类
/**
* Establish connection either directly or through a tunnel and retry in case of
* a recoverable I/O failure
*/
private void tryConnect(
final RoutedRequest req, final HttpContext context) throws HttpException, IOException {
HttpRoute route = req.getRoute();
HttpRequest wrapper = req.getRequest();
int connectCount = 0;
for (;;) {
context.setAttribute(ExecutionContext.HTTP_REQUEST, wrapper);
// Increment connect count
connectCount++;
try {
if (!managedConn.isOpen()) {
managedConn.open(route, context, params);
} else {
managedConn.setSocketTimeout(HttpConnectionParams.getSoTimeout(params));
}
establishRoute(route, context);
break;
} catch (IOException ex) {
try {
managedConn.close();
} catch (IOException ignore) {
}
if (retryHandler.retryRequest(ex, connectCount, context)) {
if (this.log.isInfoEnabled()) {
this.log.info("I/O exception ("+ ex.getClass().getName() +
") caught when connecting to the target host: "
+ ex.getMessage());
if (this.log.isDebugEnabled()) {
this.log.debug(ex.getMessage(), ex);
}
this.log.info("Retrying connect");
}
} else {
throw ex;
}
}
}
}
示例14: select
import org.apache.http.protocol.HttpContext; //导入方法依赖的package包/类
@Override
public Queue<AuthOption> select(final Map<String, Header> challenges, final HttpHost authhost, final HttpResponse response, final HttpContext context) throws MalformedChallengeException {
final HttpClientContext clientContext = HttpClientContext.adapt(context);
final Queue<AuthOption> options = new LinkedList<AuthOption>();
final Lookup<AuthSchemeProvider> registry = clientContext.getAuthSchemeRegistry();
if(registry == null) {
return options;
}
final RequestConfig config = clientContext.getRequestConfig();
Collection<String> authPrefs = config.getProxyPreferredAuthSchemes();
if(authPrefs == null) {
authPrefs = DEFAULT_SCHEME_PRIORITY;
}
if(log.isDebugEnabled()) {
log.debug("Authentication schemes in the order of preference: " + authPrefs);
}
for(final String id : authPrefs) {
final Header challenge = challenges.get(id.toLowerCase(Locale.ROOT));
if(challenge != null) {
final AuthSchemeProvider authSchemeProvider = registry.lookup(id);
if(authSchemeProvider == null) {
continue;
}
final AuthScheme authScheme = authSchemeProvider.create(context);
authScheme.processChallenge(challenge);
final Credentials saved = keychain.getCredentials(authhost.getHostName());
if(StringUtils.isEmpty(saved.getPassword())) {
try {
final Credentials input = prompt.prompt(bookmark,
StringUtils.EMPTY,
String.format("%s %s", LocaleFactory.localizedString("Login", "Login"), authhost.getHostName()),
authScheme.getRealm(),
new LoginOptions()
.icon(bookmark.getProtocol().disk())
.usernamePlaceholder(LocaleFactory.localizedString("Username", "Credentials"))
.passwordPlaceholder(LocaleFactory.localizedString("Password", "Credentials"))
.user(true).password(true)
);
if(input.isSaved()) {
context.setAttribute(PROXY_CREDENTIALS_INPUT_ID, input);
}
options.add(new AuthOption(authScheme, new NTCredentials(input.getUsername(), input.getPassword(),
preferences.getProperty("webdav.ntlm.workstation"), preferences.getProperty("webdav.ntlm.domain"))));
}
catch(LoginCanceledException ignored) {
// Ignore dismiss of prompt
throw new MalformedChallengeException(ignored.getMessage(), ignored);
}
}
else {
options.add(new AuthOption(authScheme, new NTCredentials(saved.getUsername(), saved.getPassword(),
preferences.getProperty("webdav.ntlm.workstation"), preferences.getProperty("webdav.ntlm.domain"))));
}
}
else {
if(log.isDebugEnabled()) {
log.debug("Challenge for " + id + " authentication scheme not available");
// Try again
}
}
}
return options;
}
示例15: restTemplate
import org.apache.http.protocol.HttpContext; //导入方法依赖的package包/类
@Bean
public RestTemplate restTemplate() {
CookieStore cookieStore = new BasicCookieStore();
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
httpContext.setAttribute(HttpClientContext.REQUEST_CONFIG, RequestConfig.custom().setRedirectsEnabled(false).build());
return new StatefullRestTemplate(httpContext);
}