List of usage examples for org.apache.http.protocol HttpContext getAttribute
Object getAttribute(String str);
From source file:com.amytech.android.library.utils.asynchttp.MyRedirectHandler.java
@Override public URI getLocationURI(final HttpResponse response, final HttpContext context) throws ProtocolException { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); }/*w w w .j a va 2s . c om*/ // get the location header to find out where to redirect to Header locationHeader = response.getFirstHeader("location"); if (locationHeader == null) { // got a redirect response, but no location header throw new ProtocolException( "Received redirect response " + response.getStatusLine() + " but no location header"); } // HERE IS THE MODIFIED LINE OF CODE String location = locationHeader.getValue().replaceAll(" ", "%20"); URI uri; try { uri = new URI(location); } catch (URISyntaxException ex) { throw new ProtocolException("Invalid redirect URI: " + location, ex); } HttpParams params = response.getParams(); // rfc2616 demands the location value be a complete URI // Location = "Location" ":" absoluteURI if (!uri.isAbsolute()) { if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) { throw new ProtocolException("Relative redirect location '" + uri + "' not allowed"); } // Adjust location URI HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (target == null) { throw new IllegalStateException("Target host not available " + "in the HTTP context"); } HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); try { URI requestURI = new URI(request.getRequestLine().getUri()); URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true); uri = URIUtils.resolve(absoluteRequestURI, uri); } catch (URISyntaxException ex) { throw new ProtocolException(ex.getMessage(), ex); } } if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) { RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS); if (redirectLocations == null) { redirectLocations = new RedirectLocations(); context.setAttribute(REDIRECT_LOCATIONS, redirectLocations); } URI redirectURI; if (uri.getFragment() != null) { try { HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); redirectURI = URIUtils.rewriteURI(uri, target, true); } catch (URISyntaxException ex) { throw new ProtocolException(ex.getMessage(), ex); } } else { redirectURI = uri; } if (redirectLocations.contains(redirectURI)) { throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'"); } else { redirectLocations.add(redirectURI); } } return uri; }
From source file:cn.com.loopj.android.http.MyRedirectHandler.java
@Override public URI getLocationURI(final HttpResponse response, final HttpContext context) throws ProtocolException { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); }//from www .j a va 2 s .c o m //get the location header to find out where to redirect to Header locationHeader = response.getFirstHeader("location"); if (locationHeader == null) { // got a redirect response, but no location header throw new ProtocolException( "Received redirect response " + response.getStatusLine() + " but no location header"); } //HERE IS THE MODIFIED LINE OF CODE String location = locationHeader.getValue().replaceAll(" ", "%20"); URI uri; try { uri = new URI(location); } catch (URISyntaxException ex) { throw new ProtocolException("Invalid redirect URI: " + location, ex); } HttpParams params = response.getParams(); // rfc2616 demands the location value be a complete URI // Location = "Location" ":" absoluteURI if (!uri.isAbsolute()) { if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) { throw new ProtocolException("Relative redirect location '" + uri + "' not allowed"); } // Adjust location URI HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (target == null) { throw new IllegalStateException("Target host not available " + "in the HTTP context"); } HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); try { URI requestURI = new URI(request.getRequestLine().getUri()); URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true); uri = URIUtils.resolve(absoluteRequestURI, uri); } catch (URISyntaxException ex) { throw new ProtocolException(ex.getMessage(), ex); } } if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) { RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS); if (redirectLocations == null) { redirectLocations = new RedirectLocations(); context.setAttribute(REDIRECT_LOCATIONS, redirectLocations); } URI redirectURI; if (uri.getFragment() != null) { try { HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); redirectURI = URIUtils.rewriteURI(uri, target, true); } catch (URISyntaxException ex) { throw new ProtocolException(ex.getMessage(), ex); } } else { redirectURI = uri; } if (redirectLocations.contains(redirectURI)) { throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'"); } else { redirectLocations.add(redirectURI); } } return uri; }
From source file:com.senseidb.svc.impl.HttpRestSenseiServiceImpl.java
private DefaultHttpClient createHttpClient(HttpRequestRetryHandler retryHandler) { HttpParams params = new BasicHttpParams(); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme(_scheme, _port, PlainSocketFactory.getSocketFactory())); ClientConnectionManager cm = new ThreadSafeClientConnManager(registry); DefaultHttpClient client = new DefaultHttpClient(cm, params); if (retryHandler == null) { retryHandler = new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= _maxRetries) { // Do not retry if over max retry count return false; }/* www. j a v a 2 s . c om*/ 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; } }; } client.setHttpRequestRetryHandler(retryHandler); client.addRequestInterceptor(new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); } } }); client.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } }); client.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration(HttpResponse response, HttpContext context) { // Honor 'keep-alive' header HeaderElementIterator it = new BasicHeaderElementIterator( response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if ((value != null) && param.equalsIgnoreCase("timeout")) { try { return Long.parseLong(value) * 1000; } catch (NumberFormatException ignore) { } } } long keepAlive = super.getKeepAliveDuration(response, context); if (keepAlive == -1) { keepAlive = _defaultKeepAliveDurationMS; } return keepAlive; } }); return client; }
From source file:org.ellis.yun.search.test.httpclient.HttpClientTest.java
/** * ??<br>/*from w w w . j a v a 2s. c om*/ * ????? * * @throws Exception */ @Test public void testHttpRetry() throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); // ?Handler HttpRequestRetryHandler mRequestRetryHandler = new HttpRequestRetryHandler() { // true? ? public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } if (executionCount > 5) { // ??? System.out.println("....."); return false; } if (exception instanceof NoHttpResponseException) { // ?? return true; } if (exception instanceof SSLHandshakeException) { // ???SSL? return false; } System.out.println("executionCount ==>" + executionCount); HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); if (idempotent) { // ? return true; } return false; } }; // Http? httpClient.setHttpRequestRetryHandler(mRequestRetryHandler); HttpGet httpGet = new HttpGet(new URI(ERR_URL1)); HttpResponse httpResponse = httpClient.execute(httpGet); String content = parseEntity(httpResponse.getEntity()); System.out.println(content); }
From source file:org.apache.nifi.remote.util.SiteToSiteRestApiClient.java
/** * Print AuthState in HttpContext for debugging purpose. * <p>//from w w w. j a v a2 s.c om * If the proxy server requires 407 and resend cycle, this method logs as followings, for Basic Auth: * <ul><li>state:UNCHALLENGED;</li> * <li>state:CHALLENGED;auth scheme:basic;credentials present</li></ul> * </p> * <p> * For Digest Auth: * <ul><li>state:UNCHALLENGED;</li> * <li>state:CHALLENGED;auth scheme:digest;credentials present</li></ul> * </p> * <p> * But if the proxy uses the same connection, it doesn't return 407, in such case * this method is called only once with: * <ul><li>state:UNCHALLENGED</li></ul> * </p> */ private void debugProxyAuthState(HttpContext context) { final AuthState proxyAuthState; if (shouldCheckProxyAuth() && logger.isDebugEnabled() && (proxyAuthState = (AuthState) context.getAttribute("http.auth.proxy-scope")) != null) { logger.debug("authProxyScope={}", proxyAuthState); } }
From source file:com.bincode.util.DefaultRedirectHandler.java
public URI getLocationURI(final HttpResponse response, final HttpContext context) throws ProtocolException { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); }/*from w ww . j a v a 2s . c om*/ //get the location header to find out where to redirect to Header locationHeader = response.getFirstHeader("location"); if (locationHeader == null) { // got a redirect response, but no location header throw new ProtocolException( "Received redirect response " + response.getStatusLine() + " but no location header"); } String location = locationHeader.getValue(); if (this.log.isDebugEnabled()) { this.log.debug("Redirect requested to location '" + location + "'"); } URI uri; try { uri = new URI(location); } catch (URISyntaxException ex) { throw new ProtocolException("Invalid redirect URI: " + location, ex); } HttpParams params = response.getParams(); // rfc2616 demands the location value be a complete URI // Location = "Location" ":" absoluteURI if (!uri.isAbsolute()) { if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) { throw new ProtocolException("Relative redirect location '" + uri + "' not allowed"); } // Adjust location URI HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (target == null) { throw new IllegalStateException("Target host not available " + "in the HTTP context"); } HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); try { URI requestURI = new URI(request.getRequestLine().getUri()); URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true); uri = URIUtils.resolve(absoluteRequestURI, uri); } catch (URISyntaxException ex) { throw new ProtocolException(ex.getMessage(), ex); } } if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) { RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS); if (redirectLocations == null) { redirectLocations = new RedirectLocations(); context.setAttribute(REDIRECT_LOCATIONS, redirectLocations); } URI redirectURI; if (uri.getFragment() != null) { try { HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); redirectURI = URIUtils.rewriteURI(uri, target, true); } catch (URISyntaxException ex) { throw new ProtocolException(ex.getMessage(), ex); } } else { redirectURI = uri; } if (redirectLocations.contains(redirectURI)) { throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'"); } else { redirectLocations.add(redirectURI); } } return uri; }
From source file:de.escidoc.core.common.business.fedora.FedoraUtility.java
/** * Returns a HttpClient object configured with credentials to access Fedora URLs. * //from w w w . j a va 2 s . co m * @return A HttpClient object configured with credentials to access Fedora URLs. * @throws de.escidoc.core.common.exceptions.system.WebserverSystemException */ DefaultHttpClient getHttpClient() throws WebserverSystemException { try { if (this.httpClient == null) { final HttpParams params = new BasicHttpParams(); ConnManagerParams.setMaxTotalConnections(params, HTTP_MAX_TOTAL_CONNECTIONS); final ConnPerRoute connPerRoute = new ConnPerRouteBean(HTTP_MAX_CONNECTIONS_PER_HOST); ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute); final Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80); final SchemeRegistry sr = new SchemeRegistry(); sr.register(http); final ClientConnectionManager cm = new ThreadSafeClientConnManager(params, sr); this.httpClient = new DefaultHttpClient(cm, params); final URL url = new URL(this.fedoraUrl); final CredentialsProvider credsProvider = new BasicCredentialsProvider(); final AuthScope authScope = new AuthScope(url.getHost(), AuthScope.ANY_PORT, AuthScope.ANY_REALM); final Credentials creds = new UsernamePasswordCredentials(this.fedoraUser, this.fedoraPassword); credsProvider.setCredentials(authScope, creds); httpClient.setCredentialsProvider(credsProvider); } // don't wait for auth request final HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() { @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { final AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); final CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); final HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); // If not auth scheme has been initialized yet if (authState.getAuthScheme() == null) { final AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); // Obtain credentials matching the target host final Credentials creds = credsProvider.getCredentials(authScope); // If found, generate BasicScheme preemptively if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }; httpClient.addRequestInterceptor(preemptiveAuth, 0); // try only BASIC auth; skip to test NTLM and DIGEST return this.httpClient; } catch (final MalformedURLException e) { throw new WebserverSystemException("Fedora URL from configuration malformed.", e); } }
From source file:cz.cesnet.shongo.connector.device.CiscoMCUConnector.java
/** * Try to login for {@link #httpClient}//from w ww . j a v a2s . c o m * * @throws CommandException when login fails */ private void loginHttp() throws CommandException { try { HttpPost request = new HttpPost(getDeviceHttpUrl("/login_change.html").toURI()); List<NameValuePair> parameters = new ArrayList<NameValuePair>(2); parameters.add(new BasicNameValuePair("user_name", authUsername)); parameters.add(new BasicNameValuePair("password", authPassword)); parameters.add(new BasicNameValuePair("ok", "OK")); request.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8")); HttpContext context = new BasicHttpContext(); HttpResponse response = httpClient.execute(request, context); HttpRequest responseRequest = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); StatusLine responseStatusLine = response.getStatusLine(); if (responseStatusLine.getStatusCode() != HttpStatus.SC_OK) { throw new RuntimeException("Wrong status " + responseStatusLine); } String responseRequestUrl = responseRequest.getRequestLine().getUri(); if (responseRequestUrl.startsWith("/index.html") || responseRequestUrl.equals("/")) { logger.info("Http login successful."); } else { throw new RuntimeException("Wrong response url " + responseRequestUrl); } } catch (Exception exception) { throw new CommandException("Http login failed", exception); } }
From source file:cz.cesnet.shongo.connector.device.CiscoMCUConnector.java
/** * Perform http request for given {@code file} * * @param file/*from w w w. j av a 2 s . c o m*/ * @return content as {@link MediaData} * @throws CommandException */ private synchronized MediaData execHttp(String file) throws CommandException { try { URL requestUrl = getDeviceHttpUrl(file); HttpGet request = new HttpGet(requestUrl.toURI()); HttpContext context = new BasicHttpContext(); HttpResponse response = httpClient.execute(request, context); HttpRequest responseRequest = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); StatusLine responseStatusLine = response.getStatusLine(); if (responseStatusLine.getStatusCode() == HttpStatus.SC_OK) { if (responseRequest.getRequestLine().getUri().startsWith("/login.html")) { // Perform login loginHttp(); // Perform the request again response = httpClient.execute(request, context); } HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { byte[] mediaContent = EntityUtils.toByteArray(responseEntity); MediaType mediaType = detector.detect(TikaInputStream.get(mediaContent), new Metadata()); return new MediaData(mediaType, mediaContent); } } throw new RuntimeException(response.getStatusLine().toString()); } catch (CommandException exception) { throw exception; } catch (Exception exception) { throw new CommandException("Http request " + file + " failed.", exception); } }
From source file:org.openiot.gsn.http.rest.RestRemoteWrapper.java
public DataField[] connectToRemote() throws IOException, ClassNotFoundException { // Create the GET request HttpGet httpget = new HttpGet(initParams.getRemoteContactPointEncoded(lastReceivedTimestamp)); // Create local execution context HttpContext localContext = new BasicHttpContext(); ///*from www . j av a 2s . c o m*/ structure = null; int tries = 0; AuthState authState = null; // if (inputStream != null) { try { if (response != null && response.getEntity() != null) { response.getEntity().consumeContent(); } inputStream.close(); inputStream = null; } catch (Exception e) { logger.debug(e.getMessage(), e); } } // while (tries < 2) { tries++; try { // Execute the GET request response = httpclient.execute(httpget, localContext); // int sc = response.getStatusLine().getStatusCode(); // if (sc == HttpStatus.SC_OK) { logger.debug(new StringBuilder().append("Wants to consume the structure packet from ") .append(initParams.getRemoteContactPoint())); inputStream = XSTREAM.createObjectInputStream(response.getEntity().getContent()); structure = (DataField[]) inputStream.readObject(); logger.warn("Connection established for: " + initParams.getRemoteContactPoint()); break; } else { if (sc == HttpStatus.SC_UNAUTHORIZED) authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); // Target host authentication required else if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); // Proxy authentication required else { logger.error(new StringBuilder().append("Unexpected GET status code returned: ").append(sc) .append("\nreason: ").append(response.getStatusLine().getReasonPhrase())); } if (authState != null) { if (initParams.getUsername() == null || (tries > 1 && initParams.getUsername() != null)) { logger.error("A valid username/password required to connect to the remote host: " + initParams.getRemoteContactPoint()); } else { AuthScope authScope = authState.getAuthScope(); logger.warn(new StringBuilder().append("Setting Credentials for host: ") .append(authScope.getHost()).append(":").append(authScope.getPort())); Credentials creds = new UsernamePasswordCredentials(initParams.getUsername(), initParams.getPassword()); httpclient.getCredentialsProvider().setCredentials(authScope, creds); } } } } catch (RuntimeException ex) { // In case of an unexpected exception you may want to abort // the HTTP request in order to shut down the underlying // connection and release it back to the connection manager. logger.warn("Aborting the HTTP GET request."); httpget.abort(); throw ex; } finally { if (structure == null) { if (response != null && response.getEntity() != null) { response.getEntity().consumeContent(); } } } } if (structure == null) throw new RuntimeException("Cannot connect to the remote host: " + initParams.getRemoteContactPoint()); return structure; }