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; }
public boolean isRedirectRequested( final HttpResponse response, final HttpContext context) { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); } int statusCode = response.getStatusLine().getStatusCode(); switch (statusCode) { case HttpStatus.SC_MOVED_TEMPORARILY: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_TEMPORARY_REDIRECT: HttpRequest request = (HttpRequest) context.getAttribute( ExecutionContext.HTTP_REQUEST); String method = request.getRequestLine().getMethod(); return method.equalsIgnoreCase(HttpGet.METHOD_NAME) || method.equalsIgnoreCase(HttpHead.METHOD_NAME); case HttpStatus.SC_SEE_OTHER: return true; default: return false; } //end of switch }
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); // If no auth scheme avaialble yet, try to initialize it preemptively if (authState.getAuthScheme() == null) { AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth"); CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.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.setAuthScheme(authScheme); authState.setCredentials(creds); } } }
public HttpRequest submitRequest(final HttpContext context) { HttpHost targetHost = (HttpHost) context.getAttribute( ExecutionContext.HTTP_TARGET_HOST); Object flag = context.getAttribute(REQUEST_SENT); if (flag == null) { // Stick some object into the context context.setAttribute(REQUEST_SENT, Boolean.TRUE); System.out.println("--------------"); System.out.println("Sending request to " + targetHost); System.out.println("--------------"); return new BasicHttpRequest("GET", "/"); } else { // No new request to submit return null; } }
public HttpRequest submitRequest(final HttpContext context) { HttpHost targetHost = (HttpHost) context.getAttribute( ExecutionContext.HTTP_TARGET_HOST); Object token = context.getAttribute(REQUEST_SENT); if (token == null) { // Stick some object into the context context.setAttribute(REQUEST_SENT, Boolean.TRUE); System.out.println("--------------"); System.out.println("Sending request to " + targetHost); System.out.println("--------------"); return new BasicHttpRequest("GET", "/"); } else { // No new request to submit return null; } }
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); // If no auth scheme has been initialized yet if (authState.getAuthScheme() == null) { CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); // Obtain credentials matching the target host Credentials credentials = credentialsProvider.getCredentials(authScope); // If found, generate BasicScheme preemptively if (credentials != null) { authState.setAuthScheme(new DiadocAuthScheme()); authState.setCredentials(credentials); } } }
@Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider)context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); // If not auth scheme has been initialized yet if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); // Obtain credentials matching the target host org.apache.http.auth.Credentials creds = credsProvider.getCredentials(authScope); // If found, generate BasicScheme preemptively if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } }
@Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider)context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); // If not auth scheme has been initialized yet if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); org.apache.http.auth.Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } }
/** * This method is used to capture Location headers after HttpClient redirect handling. */ private void setupClient(final AbstractHttpClient client) { this.client.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { Header header = response.getFirstHeader("Location"); if (header!=null) { String location = header.getValue(); /* * Append the base name to the Location header */ if (location.startsWith("/")) { String baseUrl = context.getAttribute(ExecutionContext.HTTP_TARGET_HOST).toString(); location = baseUrl + location; } context.setAttribute("Location", location); } } }); }
private HttpResponse handleCacheHit(final HttpHost target, final HttpRequestWrapper request, final HttpContext context, final HttpCacheEntry entry) throws ClientProtocolException, IOException { recordCacheHit(target, request); HttpResponse out = null; final Date now = getCurrentDate(); if (suitabilityChecker.canCachedResponseBeUsed(target, request, entry, now)) { log.debug("Cache hit"); out = generateCachedResponse(request, context, entry, now); } else if (!mayCallBackend(request)) { log.debug("Cache entry not suitable but only-if-cached requested"); out = generateGatewayTimeout(context); } else { log.debug("Revalidating cache entry"); return revalidateCacheEntry(target, request, context, entry, now); } if (context != null) { context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target); context.setAttribute(ExecutionContext.HTTP_REQUEST, request); context.setAttribute(ExecutionContext.HTTP_RESPONSE, out); context.setAttribute(ExecutionContext.HTTP_REQ_SENT, Boolean.TRUE); } return out; }
@Override public boolean isRedirectRequested( final HttpResponse response, final HttpContext context) { Args.notNull(response, "HTTP response"); final int statusCode = response.getStatusLine().getStatusCode(); switch (statusCode) { case HttpStatus.SC_MOVED_TEMPORARILY: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_TEMPORARY_REDIRECT: final HttpRequest request = (HttpRequest) context.getAttribute( ExecutionContext.HTTP_REQUEST); final String method = request.getRequestLine().getMethod(); return method.equalsIgnoreCase(HttpGet.METHOD_NAME) || method.equalsIgnoreCase(HttpHead.METHOD_NAME); case HttpStatus.SC_SEE_OTHER: return true; default: return false; } //end of switch }
@Override public void process( final HttpRequest request, final HttpContext context ) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute( ClientContext.TARGET_AUTH_STATE ); CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute( ClientContext.CREDS_PROVIDER ); HttpHost targetHost = (HttpHost) context.getAttribute( ExecutionContext.HTTP_TARGET_HOST ); // If not auth scheme has been initialized yet if( authState.getAuthScheme() == null ) { AuthScope authScope = new AuthScope( targetHost.getHostName(), targetHost.getPort() ); // Obtain credentials matching the target host Credentials creds = credsProvider.getCredentials( authScope ); // If found, generate BasicScheme preemptively if( creds != null ) { authState.setAuthScheme( new BasicScheme() ); authState.setCredentials( creds ); } } }
@Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context .getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context .getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } }
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.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 (requestMethod.equals(HttpPut.METHOD_NAME) || requestMethod.equals(HttpPost.METHOD_NAME)) { CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.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); } }
@Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.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(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authScheme != null) { Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort())); if (creds != null) { authState.setAuthScheme(authScheme); authState.setCredentials(creds); } } } }
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { // 设置恢复策略,在发生异常时候将自动重试3次 if (executionCount >= 3) { // 如果连接次数超过了最大值则停止重试 return false; } if (exception instanceof NoHttpResponseException) { // 如果服务器连接失败重试 return true; } if (exception instanceof SSLHandshakeException) { // 不要重试ssl连接异常 return false; } HttpRequest request = (HttpRequest) context .getAttribute(ExecutionContext.HTTP_REQUEST); boolean idempotent = (request instanceof HttpEntityEnclosingRequest); if (!idempotent) { // 重试,如果请求是考虑幂等 return true; } return false; }
public URL getTargetURL() { URL start = getURL(); HttpUriRequest req = (HttpUriRequest) context.getAttribute( ExecutionContext.HTTP_REQUEST); URI uri = req.getURI(); String path=uri.getPath(); String query=uri.getQuery(); if(!StringUtil.isEmpty(query)) path+="?"+query; URL _url=start; try { _url = new URL(start.getProtocol(),start.getHost(),start.getPort(),path); } catch (MalformedURLException e) {} return _url; }
@Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); Credentials creds; if (authState.getAuthScheme() == null) { AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth"); CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authScheme != null) { creds = credsProvider.getCredentials(new AuthScope( targetHost.getHostName(), targetHost.getPort())); if (creds == null) { throw new HttpException("No credentials for preemptive authentication"); } authState.update(authScheme, creds); } } }
private void detectRedirect(String originalUrl, Context context, HttpContext httpContext) { HttpUriRequest request = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost host = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); // Sometimes the request doesn't contain the "http://host" part so we // must take from the HttpHost object. String redirectedUrl; if (request.getURI().getScheme() == null) { redirectedUrl = host.toURI() + request.getURI(); } else { redirectedUrl = request.getURI().toString(); } redirectFrom = originalUrl.substring(0, originalUrl.indexOf("/rest/")); redirectTo = redirectedUrl.substring(0, redirectedUrl.indexOf("/rest/")); LOG.info(redirectFrom + " redirects to " + redirectTo); redirectionLastChecked = System.currentTimeMillis(); redirectionNetworkType = getCurrentNetworkType(context); }
private String getContentFromUrl(String url) throws IOException { MainApplication appContext = (MainApplication) context.getApplicationContext(); HttpClient client = appContext.getHttpClient(isForumJV ? MainApplication.JVFORUM_SESSION : MainApplication.JVC_SESSION); HttpGet httpGet = new HttpGet(url); HttpContext httpContext = new BasicHttpContext(); HttpResponse response = client.execute(httpGet, httpContext); HttpEntity entity = response.getEntity(); String redirectedUrl = ((HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST)).getURI().toString(); if(isForumJV) { requestRedirectedUrl = baseUrl + redirectedUrl.substring(1); } else { requestRedirectedUrl = "http://www.jeuxvideo.com" + redirectedUrl; } return MainApplication.getEntityContent(entity); }
public String getContentFromUrl(String url, int auth_type) throws IOException { MainApplication app = (MainApplication) forum.getContext().getApplicationContext(); HttpClient client = app.getHttpClient(auth_type); HttpContext httpContext = new BasicHttpContext(); HttpEntity entity = client.execute(new HttpGet(url), httpContext).getEntity(); String redirectedUrl = ((HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST)).getURI().toString(); if(forum.isForumJV()) { requestRedirectedUrl = forum.getBaseUrl() + redirectedUrl.substring(1); } else { requestRedirectedUrl = "http://www.jeuxvideo.com" + redirectedUrl; } return MainApplication.getEntityContent(entity); }
@Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context .getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context .getAttribute(ExecutionContext.HTTP_TARGET_HOST); // If not auth scheme has been initialized yet if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); // Obtain credentials matching the target host org.apache.http.auth.Credentials creds = credsProvider .getCredentials(authScope); // If found, generate BasicScheme preemptively if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } }
protected boolean retryRequest(final HttpContext context) { final HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); final Object obj = context.getAttribute(ExecutionContext.HTTP_REQ_SENT); final boolean isSent = obj == null ? false : (Boolean) obj; if (requestIsAborted(request)) { return false; } if (handleAsIdempotent(request)) { // Retry if the request is considered idempotent return true; } if (!isSent || this.requestSentRetryEnabled) { // Retry if the request has not been sent fully or // if it's OK to retry methods that have been sent return true; } return false; }
public void commit() throws IOException, HttpException { if (this.commited) { return; } this.commited = true; this.context.setAttribute(ExecutionContext.HTTP_CONNECTION, this.conn); this.context.setAttribute(ExecutionContext.HTTP_RESPONSE, this.response); BasicHttpEntity entity = new BasicHttpEntity(); entity.setChunked(true); entity.setContentType(this.contentType); this.response.setEntity(entity); this.httpproc.process(this.response, this.context); this.conn.sendResponse(this.response); }
/** * * This function adds support for pre-emptive HTTP Authentication for an HttpClient. * * @param httpClient */ public static void makeAuthenticationPreemptive(HttpClient httpClient) { HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() { public void process(final HttpRequest request,final HttpContext context) throws HttpException,IOException{ AuthState authState = (AuthState) context .getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context .getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }; ((AbstractHttpClient) httpClient).addRequestInterceptor(preemptiveAuth,0); }
@SuppressWarnings("deprecation") public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { // Get the AuthState AuthState authState = (AuthState) context.getAttribute(ClientContext.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(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.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.setAuthScheme(authScheme); authState.setCredentials(creds); } } }
public void process(final HttpRequest request, final HttpContext context) { AuthState authState = (AuthState) context.getAttribute( ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute( ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute( ExecutionContext.HTTP_TARGET_HOST); // If not auth scheme has been initialized yet if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); // Obtain credentials matching the target host Credentials creds = credsProvider.getCredentials(authScope); // If found, generate BasicScheme preemptively if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } }
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { // 设置恢复策略,在发生异常时候将自动重试errorRetryCount次 if (executionCount >= errorRetryCount) { // Do not retry if over max retry count System.out.println("errors"); return false; } if (exception instanceof NoHttpResponseException) { // Retry if the server dropped connection on us return true; } if (exception instanceof SSLHandshakeException) { // Do not retry on SSL handshake exception return false; } HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); boolean idempotent = (request instanceof HttpEntityEnclosingRequest); if (!idempotent) { // Retry if the request is considered idempotent return true; } return false; }
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.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( ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.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.setAuthScheme(authScheme); authState.setCredentials(creds); } } }
public void setAuthPreemtive(boolean authPreemtive) { /** * Add an HttpRequestInterceptor that will perform preemptive authentication * @see http://hc.apache.org/httpcomponents-client-4.0.1/tutorial/html/authentication.html */ HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws IOException { AuthState authState = (AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider)context.getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); // If not authentication scheme has been initialized yet if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); // Obtain credentials matching the target host Credentials creds = credsProvider.getCredentials(authScope); // If found, generate BasicScheme preemptively if (creds != null) { authState.update(new BasicScheme(), creds); } } } }; m_httpClient.addRequestInterceptor(preemptiveAuth, 0); }
/** * If no auth scheme has been selected for the given context, consider each * of the preferred auth schemes and select the first one for which an * AuthScheme and matching Credentials are available. */ public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); if (authState != null && authState.getAuthScheme() != null) { return; } HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); CredentialsProvider creds = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER); AuthSchemeRegistry schemes = (AuthSchemeRegistry) context.getAttribute(ClientContext.AUTHSCHEME_REGISTRY); for (Object schemeName : (Iterable) context.getAttribute(ClientContext.AUTH_SCHEME_PREF)) { AuthScheme scheme = schemes.getAuthScheme(schemeName.toString(), request.getParams()); if (scheme != null) { AuthScope targetScope = new AuthScope(target.getHostName(), target.getPort(), scheme.getRealm(), scheme .getSchemeName()); Credentials cred = creds.getCredentials(targetScope); if (cred != null) { authState.setAuthScheme(scheme); authState.setCredentials(cred); return; } } } }