當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpClientContext類代碼示例

本文整理匯總了Java中org.apache.http.client.protocol.HttpClientContext的典型用法代碼示例。如果您正苦於以下問題:Java HttpClientContext類的具體用法?Java HttpClientContext怎麽用?Java HttpClientContext使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


HttpClientContext類屬於org.apache.http.client.protocol包,在下文中一共展示了HttpClientContext類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: DatarouterHttpResponse

import org.apache.http.client.protocol.HttpClientContext; //導入依賴的package包/類
public DatarouterHttpResponse(HttpResponse response, HttpClientContext context,
		Consumer<HttpEntity> httpEntityConsumer){
	this.response = response;
	this.cookies = context.getCookieStore().getCookies();
	if(response != null){
		this.statusCode = response.getStatusLine().getStatusCode();
		this.entity = "";

		HttpEntity httpEntity = response.getEntity();
		if(httpEntity == null){
			return;
		}
		if(httpEntityConsumer != null){
			httpEntityConsumer.accept(httpEntity);
			return;
		}
		try{
			this.entity = EntityUtils.toString(httpEntity);
		}catch(IOException e){
			logger.error("Exception occurred while reading HTTP response entity", e);
		}finally{
			EntityUtils.consumeQuietly(httpEntity);
		}
	}
}
 
開發者ID:hotpads,項目名稱:datarouter,代碼行數:26,代碼來源:DatarouterHttpResponse.java

示例2: process

import org.apache.http.client.protocol.HttpClientContext; //導入依賴的package包/類
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {

            AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);

            if (authState.getAuthScheme() != null || authState.hasAuthOptions()) {
                return;
            }

            // If no authState has been established and this is a PUT or POST request, add preemptive authorisation
            String requestMethod = request.getRequestLine().getMethod();
            if (alwaysSendAuth || requestMethod.equals(HttpPut.METHOD_NAME) || requestMethod.equals(HttpPost.METHOD_NAME)) {
                CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(HttpClientContext.CREDS_PROVIDER);
                HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
                Credentials credentials = credentialsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
                if (credentials == null) {
                    throw new HttpException("No credentials for preemptive authentication");
                }
                authState.update(authScheme, credentials);
            }
        }
 
開發者ID:lxxlxx888,項目名稱:Reer,代碼行數:21,代碼來源:HttpClientConfigurer.java

示例3: ResponseWrap

import org.apache.http.client.protocol.HttpClientContext; //導入依賴的package包/類
public ResponseWrap(CloseableHttpClient httpClient, HttpRequestBase request, CloseableHttpResponse response, HttpClientContext context,
		ObjectMapper _mapper) {
	this.response = response;
	this.httpClient = httpClient;
	this.request = request;
	this.context = context;
	mapper = _mapper;

	try {
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			this.entity = new BufferedHttpEntity(entity);
		} else {
			this.entity = new BasicHttpEntity();
		}

		EntityUtils.consumeQuietly(entity);
		this.response.close();
	} catch (IOException e) {
		logger.warn(e.getMessage());
	}
}
 
開發者ID:swxiao,項目名稱:bubble2,代碼行數:23,代碼來源:ResponseWrap.java

示例4: resolveHttpRedirects

import org.apache.http.client.protocol.HttpClientContext; //導入依賴的package包/類
/** Return final location from http redirects  */
public static String resolveHttpRedirects(String uri) 
        throws IOException, URISyntaxException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpClientContext context = HttpClientContext.create();
    HttpGet httpget = new HttpGet(uri);
    //httpget.addHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:17.0) Gecko/20121202 Firefox/17.0 Iceweasel/17.0.1");        
    CloseableHttpResponse response = httpclient.execute(httpget, context);          
    try {
        HttpHost target = context.getTargetHost();
        List<URI> redirectLocations = context.getRedirectLocations();
        URI location = URIUtils.resolve(httpget.getURI(), target, redirectLocations);
        return location.toString();
    } finally {
        response.close();           
    }                
}
 
開發者ID:dkorenci,項目名稱:feedsucker,代碼行數:18,代碼來源:HttpUtils.java

示例5: connect

import org.apache.http.client.protocol.HttpClientContext; //導入依賴的package包/類
public Map<String, String> connect(String url, Map<String, Object> parameters) throws ManagerResponseException {

        Map<String, String> response = new HashMap<String, String>();
        CloseableHttpClient httpclient = HttpClients.createDefault();
        List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("j_username", (String) parameters.get("login")));
        nvps.add(new BasicNameValuePair("j_password", (String) parameters.get("password")));
        localContext = HttpClientContext.create();
        localContext.setCookieStore(new BasicCookieStore());
        HttpPost httpPost = new HttpPost(url);
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
            CloseableHttpResponse httpResponse = httpclient.execute(httpPost, localContext);
            ResponseHandler<String> handler = new CustomResponseErrorHandler();
            String body = handler.handleResponse(httpResponse);
            response.put(BODY, body);
            httpResponse.close();
        } catch (Exception e) {
            authentificationUtils.getMap().clear();
            throw new ManagerResponseException(e.getMessage(), e);
        }

        return response;
    }
 
開發者ID:oncecloud,項目名稱:devops-cstack,代碼行數:25,代碼來源:RestUtils.java

示例6: retryRequest

import org.apache.http.client.protocol.HttpClientContext; //導入依賴的package包/類
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context){
	if(logOnRetry){
		HttpClientContext clientContext = HttpClientContext.adapt(context);
		logger.warn("Request {} failure Nº {}", clientContext.getRequest().getRequestLine(), executionCount,
				exception);
	}
	Object retrySafe = context.getAttribute(RETRY_SAFE_ATTRIBUTE);
	if(retrySafe == null || !(retrySafe instanceof Boolean) || !(Boolean)retrySafe || executionCount > retryCount){
		return false;
	}
	return true;
}
 
開發者ID:hotpads,項目名稱:datarouter,代碼行數:14,代碼來源:DatarouterHttpRetryHandler.java

示例7: authSucceeded

import org.apache.http.client.protocol.HttpClientContext; //導入依賴的package包/類
@Override
public void authSucceeded(final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) {
    final HttpClientContext clientContext = HttpClientContext.adapt(context);
    final Credentials credentials = clientContext.getAttribute(PROXY_CREDENTIALS_INPUT_ID, Credentials.class);
    if(null != credentials) {
        clientContext.removeAttribute(PROXY_CREDENTIALS_INPUT_ID);
        if(log.isInfoEnabled()) {
            log.info(String.format("Save passphrase for proxy %s", authhost));
        }
        keychain.addCredentials(authhost.getHostName(), credentials.getUsername(), credentials.getPassword());
    }
    super.authSucceeded(authhost, authScheme, context);
}
 
開發者ID:iterate-ch,項目名稱:cyberduck,代碼行數:14,代碼來源:CallbackProxyAuthenticationStrategy.java

示例8: retryRequest

import org.apache.http.client.protocol.HttpClientContext; //導入依賴的package包/類
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {

    if (executionCount >= 3) {// 如果已經重試了3次,就放棄
        return false;
    }

    if (exception instanceof NoHttpResponseException) {// 如果服務器丟掉了連接,那麽就重試
        return true;
    }

    if (exception instanceof SSLHandshakeException) {// 不要重試SSL握手異常
        return false;
    }

    if (exception instanceof InterruptedIOException) {// 超時
        return true;
    }

    if (exception instanceof UnknownHostException) {// 目標服務器不可達
        return false;
    }

    if (exception instanceof ConnectTimeoutException) {// 連接被拒絕
        return false;
    }

    if (exception instanceof SSLException) {// ssl握手異常
        return false;
    }

    HttpClientContext clientContext = HttpClientContext.adapt(context);
    HttpRequest request = clientContext.getRequest();

    // 如果請求是冪等的,就再次嘗試
    if (!(request instanceof HttpEntityEnclosingRequest)) {
        return true;
    }
    return false;
}
 
開發者ID:fengzhizi715,項目名稱:PicCrawler,代碼行數:41,代碼來源:RetryHandler.java

示例9: execute

import org.apache.http.client.protocol.HttpClientContext; //導入依賴的package包/類
/**
 * 執行請求
 * 
 * @date 2015年7月17日
 * @return
 */
public ResponseWrap execute() {
	settingRequest();
	if (httpClient == null) {
		httpClient = clientBuilder.build();
	}

	try {
		HttpClientContext context = HttpClientContext.create();
		CloseableHttpResponse response = httpClient.execute(request, context);
		return new ResponseWrap(httpClient, request, response, context, mapper);
	} catch (IOException e) {
		logger.error(e.getMessage(), e);
		throw new RuntimeException(e.getMessage(), e);
	}
}
 
開發者ID:swxiao,項目名稱:bubble2,代碼行數:22,代碼來源:HttpUtils.java

示例10: addPreemptiveAuthenticationProxy

import org.apache.http.client.protocol.HttpClientContext; //導入依賴的package包/類
private static void addPreemptiveAuthenticationProxy(HttpClientContext clientContext,
                                                     ProxyConfiguration proxyConfiguration) {

    if (proxyConfiguration.preemptiveBasicAuthenticationEnabled()) {
        HttpHost targetHost = new HttpHost(proxyConfiguration.endpoint().getHost(), proxyConfiguration.endpoint().getPort());
        final CredentialsProvider credsProvider = newProxyCredentialsProvider(proxyConfiguration);
        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        clientContext.setCredentialsProvider(credsProvider);
        clientContext.setAuthCache(authCache);
    }
}
 
開發者ID:aws,項目名稱:aws-sdk-java-v2,代碼行數:17,代碼來源:ApacheUtils.java

示例11: newClientContext

import org.apache.http.client.protocol.HttpClientContext; //導入依賴的package包/類
/**
 * Returns a new HttpClientContext used for request execution.
 */
public static HttpClientContext newClientContext(HttpClientSettings settings,
                                                 Map<String, ? extends Object>
                                                         attributes) {
    final HttpClientContext clientContext = new HttpClientContext();

    if (attributes != null && !attributes.isEmpty()) {
        for (Map.Entry<String, ?> entry : attributes.entrySet()) {
            clientContext.setAttribute(entry.getKey(), entry.getValue());
        }
    }

    addPreemptiveAuthenticationProxy(clientContext, settings);
    return clientContext;

}
 
開發者ID:IBM,項目名稱:ibm-cos-sdk-java,代碼行數:19,代碼來源:ApacheUtils.java

示例12: addPreemptiveAuthenticationProxy

import org.apache.http.client.protocol.HttpClientContext; //導入依賴的package包/類
private static void addPreemptiveAuthenticationProxy(HttpClientContext clientContext,
                                                     HttpClientSettings settings) {

    if (settings.isPreemptiveBasicProxyAuth()) {
        HttpHost targetHost = new HttpHost(settings.getProxyHost(), settings
                .getProxyPort());
        final CredentialsProvider credsProvider = newProxyCredentialsProvider(settings);
        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        clientContext.setCredentialsProvider(credsProvider);
        clientContext.setAuthCache(authCache);
    }
}
 
開發者ID:IBM,項目名稱:ibm-cos-sdk-java,代碼行數:18,代碼來源:ApacheUtils.java

示例13: determineProxy

import org.apache.http.client.protocol.HttpClientContext; //導入依賴的package包/類
@Override
protected HttpHost determineProxy(HttpHost host, HttpRequest request, HttpContext context) throws HttpException {
    HttpClientContext httpClientContext = HttpClientContext.adapt(context);
    Proxy proxy = proxyPlanner.determineProxy(host, request, context, ipPool, crawlerSession);

    if (proxy == null) {
        return null;
    }
    if (log.isDebugEnabled()) {
        log.debug("{} 當前使用IP為:{}:{}", host.getHostName(), proxy.getIp(), proxy.getPort());
    }
    context.setAttribute(VSCRAWLER_AVPROXY_KEY, proxy);

    if (proxy.getAuthenticationHeaders() != null) {
        for (Header header : proxy.getAuthenticationHeaders()) {
            request.addHeader(header);
        }
    }

    if (StringUtils.isNotEmpty(proxy.getUsername()) && StringUtils.isNotEmpty(proxy.getPassword())) {
        BasicCredentialsProvider credsProvider1 = new BasicCredentialsProvider();
        httpClientContext.setCredentialsProvider(credsProvider1);
        credsProvider1.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword()));
    }
    return new HttpHost(proxy.getIp(), proxy.getPort());
}
 
開發者ID:virjar,項目名稱:vscrawler,代碼行數:28,代碼來源:VSCrawlerRoutePlanner.java

示例14: execute

import org.apache.http.client.protocol.HttpClientContext; //導入依賴的package包/類
@Override
public CloseableHttpResponse execute(HttpRoute route, HttpRequestWrapper request, HttpClientContext clientContext,
        HttpExecutionAware execAware) throws IOException, HttpException {
    Proxy proxy = (Proxy) clientContext.getAttribute(VSCrawlerConstant.VSCRAWLER_AVPROXY_KEY);
    if (proxy != null) {
        proxy.recordUsage();
    }
    try {
        return delegate.execute(route, request, clientContext, execAware);
    } catch (IOException ioe) {
        if (proxy != null) {
            proxy.recordFailed();
        }
        throw ioe;
    }
}
 
開發者ID:virjar,項目名稱:vscrawler,代碼行數:17,代碼來源:ProxyFeedBackClientExecChain.java

示例15: determineProxy

import org.apache.http.client.protocol.HttpClientContext; //導入依賴的package包/類
@Override
public Proxy determineProxy(HttpHost host, HttpRequest request, HttpContext context, IPPool ipPool,
        CrawlerSession crawlerSession) {
    HttpClientContext httpClientContext = HttpClientContext.adapt(context);

    Proxy proxy = (Proxy) crawlerSession.getExtInfo(VSCRAWLER_AVPROXY_KEY);
    if (proxy == null) {
        String accessUrl = null;
        if (request instanceof HttpRequestWrapper || request instanceof HttpGet) {
            accessUrl = HttpUriRequest.class.cast(request).getURI().toString();
        }
        if (!PoolUtil.isDungProxyEnabled(httpClientContext)) {
            log.info("{}不會被代理", accessUrl);
            return null;
        }
        proxy = ipPool.getIP(host.getHostName(), accessUrl);
        if (proxy == null) {
            return null;
        }
        crawlerSession.setExtInfo(VSCRAWLER_AVPROXY_KEY, proxy);
    }

    return proxy;
}
 
開發者ID:virjar,項目名稱:vscrawler,代碼行數:25,代碼來源:EverySessionPlanner.java


注:本文中的org.apache.http.client.protocol.HttpClientContext類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。