List of usage examples for org.apache.http.protocol ExecutionContext HTTP_TARGET_HOST
String HTTP_TARGET_HOST
To view the source code for org.apache.http.protocol ExecutionContext HTTP_TARGET_HOST.
Click Source Link
From source file:android.core.TestHttpClient.java
public HttpResponse execute(final HttpRequest request, final HttpHost targetHost, final HttpClientConnection conn) throws HttpException, IOException { this.context.setAttribute(ExecutionContext.HTTP_REQUEST, request); this.context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost); this.context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); request.setParams(new DefaultedHttpParams(request.getParams(), this.params)); this.httpexecutor.preProcess(request, this.httpproc, this.context); HttpResponse response = this.httpexecutor.execute(request, conn, this.context); response.setParams(new DefaultedHttpParams(response.getParams(), this.params)); this.httpexecutor.postProcess(response, this.httpproc, this.context); return response; }
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 ww w. j a va2 s . 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:com.unboundid.scim.sdk.PreemptiveAuthInterceptor.java
/** * {@inheritDoc}//from w w w. ja va 2 s . c o m */ @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (target.getPort() < 0) { SchemeRegistry schemeRegistry = (SchemeRegistry) context.getAttribute(ClientContext.SCHEME_REGISTRY); Scheme scheme = schemeRegistry.getScheme(target); target = new HttpHost(target.getHostName(), scheme.resolvePort(target.getPort()), target.getSchemeName()); } AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE); if (authCache == null) { authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(target, basicAuth); context.setAttribute(ClientContext.AUTH_CACHE, authCache); return; } CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); if (credsProvider == null) { return; } final AuthState targetState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); if (targetState != null && targetState.getState() == AuthProtocolState.UNCHALLENGED) { final AuthScheme authScheme = authCache.get(target); if (authScheme != null) { doPreemptiveAuth(target, authScheme, targetState, credsProvider); } } final HttpHost proxy = (HttpHost) context.getAttribute(ExecutionContext.HTTP_PROXY_HOST); final AuthState proxyState = (AuthState) context.getAttribute(ClientContext.PROXY_AUTH_STATE); if (proxy != null && proxyState != null && proxyState.getState() == AuthProtocolState.UNCHALLENGED) { final AuthScheme authScheme = authCache.get(proxy); if (authScheme != null) { doPreemptiveAuth(proxy, authScheme, proxyState, credsProvider); } } }
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"); }//from www . ja va 2 s . com // 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.adrup.saldo.bank.lf.LfBankManager.java
@Override public Map<AccountHashKey, RemoteAccount> getAccounts(Map<AccountHashKey, RemoteAccount> accounts) throws BankException { Log.d(TAG, "getAccounts()"); HttpClient httpClient = new SaldoHttpClient(mContext); try {/*from w w w .j a va 2 s. co m*/ // get login page Log.d(TAG, "getting login page"); HttpContext httpContext = new BasicHttpContext(); String res = HttpHelper.get(httpClient, LOGIN_URL, httpContext); HttpUriRequest currentReq = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost currentHost = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); String action = currentHost.toURI() + currentReq.getURI(); Log.e(TAG, "action=" + action); Matcher matcher = Pattern.compile(VIEWSTATE_REGEX).matcher(res); if (!matcher.find()) { Log.e(TAG, "No viewstate match."); Log.d(TAG, res); throw new LfBankException("No viewState match."); } String viewState = matcher.group(1); Log.d(TAG, "viewState= " + viewState); matcher = Pattern.compile(EVENTVALIDATION_REGEX).matcher(res); if (!matcher.find()) { Log.e(TAG, "No eventvalidation match."); Log.d(TAG, res); throw new LfBankException("No eventValidation match."); } String eventValidation = matcher.group(1); Log.d(TAG, "eventValidation= " + eventValidation); // do login post List<NameValuePair> parameters = new ArrayList<NameValuePair>(3); parameters.add(new BasicNameValuePair("__LASTFOCUS", "")); parameters.add(new BasicNameValuePair("__EVENTTARGET", "")); parameters.add(new BasicNameValuePair("__EVENTARGUMENT", "")); parameters.add(new BasicNameValuePair(VIEWSTATE_PARAM, viewState)); parameters.add(new BasicNameValuePair("selMechanism", "PIN-kod")); parameters.add(new BasicNameValuePair(USER_PARAM, mBankLogin.getUsername())); parameters.add(new BasicNameValuePair(PASS_PARAM, mBankLogin.getPassword())); parameters.add(new BasicNameValuePair("btnLogIn.x", "39")); parameters.add(new BasicNameValuePair("btnLogIn.y", "11")); parameters.add(new BasicNameValuePair(EVENTVALIDATION_PARAM, eventValidation)); Log.d(TAG, "logging in..."); res = HttpHelper.post(httpClient, action, parameters); if (res.contains("Felaktig inloggning")) { Log.d(TAG, "auth fail"); throw new AuthenticationException("auth fail"); } Log.d(TAG, "getting accountsUrl"); // token matcher = Pattern.compile(TOKEN_REGEX).matcher(res); if (!matcher.find()) { Log.e(TAG, "No token match."); Log.d(TAG, res); throw new LfBankException("No token match."); } String token = matcher.group(1); Log.d(TAG, "token= " + token); // accountsUrl matcher = Pattern.compile(ACCOUNTS_URL_REGEX).matcher(res); if (!matcher.find()) { Log.e(TAG, "No accountsUrl match."); Log.d(TAG, res); throw new LfBankException("No accountsUrl match."); } String accountsUrl = Html.fromHtml(matcher.group(1)).toString(); accountsUrl += "&_token=" + token; Log.d(TAG, "tokenized accountsUrl= " + accountsUrl); // get accounts page Log.d(TAG, "fetching accounts"); res = HttpHelper.get(httpClient, accountsUrl); matcher = Pattern.compile(ACCOUNTS_REGEX).matcher(res); int remoteId = 1; int count = 0; while (matcher.find()) { count++; int groupCount = matcher.groupCount(); for (int i = 1; i <= groupCount; i++) { Log.d(TAG, i + ":" + matcher.group(i)); } if (groupCount < 2) { throw new BankException("Pattern match issue: groupCount < 2"); } int ordinal = remoteId; String name = Html.fromHtml(matcher.group(1)).toString(); long balance = Long.parseLong(matcher.group(2).replaceAll("\\,|\\.| ", "")) / 100; accounts.put(new AccountHashKey(String.valueOf(remoteId), mBankLogin.getId()), new Account(String.valueOf(remoteId), mBankLogin.getId(), ordinal, name, balance)); remoteId++; } if (count == 0) { Log.d(TAG, "no accounts added"); Log.d(TAG, res); } } catch (IOException e) { Log.e(TAG, e.getMessage(), e); throw new LfBankException(e.getMessage(), e); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); throw new LfBankException(e.getMessage(), e); } finally { httpClient.getConnectionManager().shutdown(); } return accounts; }
From source file:fr.ippon.wip.http.hc.TransformerResponseInterceptor.java
/** * If httpResponse must be transformed, creates an instance of * WIPTransformer, executes WIPTransformer#transform on the response content * and updates the response entity accordingly. * /*from w ww .j a v a2s . c o m*/ * @param httpResponse * @param context * @throws HttpException * @throws IOException */ public void process(HttpResponse httpResponse, HttpContext context) throws HttpException, IOException { PortletRequest portletRequest = HttpClientResourceManager.getInstance().getCurrentPortletRequest(); PortletResponse portletResponse = HttpClientResourceManager.getInstance().getCurrentPortletResponse(); WIPConfiguration config = WIPUtil.getConfiguration(portletRequest); RequestBuilder request = HttpClientResourceManager.getInstance().getCurrentRequest(); if (httpResponse == null) { // No response -> no transformation LOG.warning("No response to transform."); return; } HttpEntity entity = httpResponse.getEntity(); if (entity == null) { // No entity -> no transformation return; } ContentType contentType = ContentType.getOrDefault(entity); String mimeType = contentType.getMimeType(); String actualURL; RedirectLocations redirectLocations = (RedirectLocations) context .getAttribute("http.protocol.redirect-locations"); if (redirectLocations != null) actualURL = Iterables.getLast(redirectLocations.getAll()).toString(); else if (context.getAttribute(CachingHttpClient.CACHE_RESPONSE_STATUS) == CacheResponseStatus.CACHE_HIT) { actualURL = request.getRequestedURL(); } else { HttpRequest actualRequest = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost actualHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); actualURL = actualHost.toURI() + actualRequest.getRequestLine().getUri(); } // Check if actual URI must be transformed if (!config.isProxyURI(actualURL)) return; // a builder for creating a WIPTransformer instance TransformerBuilder transformerBuilder = new TransformerBuilder().setActualURL(actualURL) .setMimeType(mimeType).setPortletRequest(portletRequest).setPortletResponse(portletResponse) .setResourceType(request.getResourceType()).setXmlReaderPool(xmlReaderPool); // Creates an instance of Transformer depending on ResourceType and // MimeType int status = transformerBuilder.build(); if (status == TransformerBuilder.STATUS_NO_TRANSFORMATION) return; WIPTransformer transformer = transformerBuilder.getTransformer(); // Call WIPTransformer#transform method and update the response Entity // object try { String content = EntityUtils.toString(entity); String transformedContent = ((AbstractTransformer) transformer).transform(content); StringEntity transformedEntity; if (contentType.getCharset() != null) { transformedEntity = new StringEntity(transformedContent, contentType); } else { transformedEntity = new StringEntity(transformedContent); } transformedEntity.setContentType(contentType.toString()); httpResponse.setEntity(transformedEntity); } catch (SAXException e) { LOG.log(Level.SEVERE, "Could not transform HTML", e); throw new IllegalArgumentException(e); } catch (TransformerException e) { LOG.log(Level.SEVERE, "Could not transform HTML", e); throw new IllegalArgumentException(e); } }
From source file:mobi.jenkinsci.ci.client.JenkinsFormAuthHttpClient.java
private void doSsoRedirect(final URL baseUrl, final HttpContext httpContext, String redirectUrl, final String otp) throws IOException { HttpResponse redirectResponse;/*from ww w. j a v a2 s .c o m*/ final HttpGet redirect2Jenkins = new HttpGet(redirectUrl); log.debug("Login SUCCEDED: redirecting back to Jenkins using " + redirect2Jenkins.getURI()); try { redirectResponse = httpClient.execute(redirect2Jenkins, httpContext); final HttpHost host = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (!host.getHostName().toLowerCase().equals(baseUrl.getHost().toLowerCase())) { redirectUrl = getSsoErrorHandler(host).doTwoStepAuthentication(httpClient, httpContext, redirectResponse, otp); doSsoRedirect(baseUrl, httpContext, redirectUrl, null); } if (redirectResponse.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) { throw new IOException("Redirection back to Jenkins failed with HTTP Status Code: " + redirectResponse.getStatusLine()); } } finally { redirect2Jenkins.releaseConnection(); } }
From source file:com.couchbase.client.ClusterManager.java
/** * Connects to a given server if a connection has not been made to at least * one of the servers in the server list already. * @param uri//w w w .ja v a 2 s. c o m * @return */ private boolean connect(URI uri) { host = new HttpHost(uri.getHost(), uri.getPort()); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, new SyncBasicHttpParams()); } return true; } catch (IOException e) { return false; } }
From source file:com.k42b3.aletheia.protocol.http.HttpProtocol.java
public void setRequest(com.k42b3.aletheia.protocol.Request request, CallbackInterface callback) throws Exception { super.setRequest(request, callback); // request settings int port = request.getUrl().getPort(); if (port == -1) { if (request.getUrl().getProtocol().equalsIgnoreCase("https")) { port = 443;/* w w w .j av a 2 s.c om*/ } else { port = 80; } } context = new BasicHttpContext(null); host = new HttpHost(request.getUrl().getHost(), port); conn = new DefaultHttpClientConnection(); connStrategy = new DefaultConnectionReuseStrategy(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); }
From source file:bigbird.benchmark.BenchmarkWorker.java
public void run() { HttpResponse response = null;/*ww w.ja va 2s.co m*/ DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); String hostname = targetHost.getHostName(); int port = targetHost.getPort(); if (port == -1) { port = 80; } // Populate the execution context this.context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); this.context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, this.targetHost); // this.context.setAttribute(ExecutionContext.HTTP_REQUEST, this.request); stats.start(); for (int i = 0; i < count; i++) { try { HttpRequest req = requestGenerator.generateRequest(count); if (!conn.isOpen()) { Socket socket = null; if ("https".equals(targetHost.getSchemeName())) { SocketFactory socketFactory = SSLSocketFactory.getDefault(); socket = socketFactory.createSocket(hostname, port); } else { socket = new Socket(hostname, port); } conn.bind(socket, params); } try { // Prepare request this.httpexecutor.preProcess(req, this.httpProcessor, this.context); // Execute request and get a response response = this.httpexecutor.execute(req, conn, this.context); // Finalize response this.httpexecutor.postProcess(response, this.httpProcessor, this.context); } catch (HttpException e) { stats.incWriteErrors(); if (this.verbosity >= 2) { System.err.println("Failed HTTP request : " + e.getMessage()); } continue; } verboseOutput(req, response); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { stats.incSuccessCount(); } else { stats.incFailureCount(); continue; } HttpEntity entity = response.getEntity(); String charset = EntityUtils.getContentCharSet(entity); if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } long contentlen = 0; if (entity != null) { InputStream instream = entity.getContent(); int l = 0; while ((l = instream.read(this.buffer)) != -1) { stats.incTotalBytesRecv(l); contentlen += l; if (this.verbosity >= 4) { String s = new String(this.buffer, 0, l, charset); System.out.print(s); } } instream.close(); } if (this.verbosity >= 4) { System.out.println(); System.out.println(); } if (!keepalive || !this.connstrategy.keepAlive(response, this.context)) { conn.close(); } stats.setContentLength(contentlen); } catch (IOException ex) { ex.printStackTrace(); stats.incFailureCount(); if (this.verbosity >= 2) { System.err.println("I/O error: " + ex.getMessage()); } } } stats.finish(); if (response != null) { Header header = response.getFirstHeader("Server"); if (header != null) { stats.setServerName(header.getValue()); } } try { conn.close(); } catch (IOException ex) { ex.printStackTrace(); stats.incFailureCount(); if (this.verbosity >= 2) { System.err.println("I/O error: " + ex.getMessage()); } } }