List of usage examples for org.apache.http.client.methods HttpUriRequest getURI
URI getURI();
From source file:org.elasticsearch.client.RestClientSingleHostTests.java
/** * Verifies the content of the {@link HttpRequest} that's internally created and passed through to the http client *///w w w. j a v a 2 s . c om @SuppressWarnings("unchecked") public void testInternalHttpRequest() throws Exception { ArgumentCaptor<HttpAsyncRequestProducer> requestArgumentCaptor = ArgumentCaptor .forClass(HttpAsyncRequestProducer.class); int times = 0; for (String httpMethod : getHttpMethods()) { HttpUriRequest expectedRequest = performRandomRequest(httpMethod); verify(httpClient, times(++times)).<HttpResponse>execute(requestArgumentCaptor.capture(), any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class)); HttpUriRequest actualRequest = (HttpUriRequest) requestArgumentCaptor.getValue().generateRequest(); assertEquals(expectedRequest.getURI(), actualRequest.getURI()); assertEquals(expectedRequest.getClass(), actualRequest.getClass()); assertArrayEquals(expectedRequest.getAllHeaders(), actualRequest.getAllHeaders()); if (expectedRequest instanceof HttpEntityEnclosingRequest) { HttpEntity expectedEntity = ((HttpEntityEnclosingRequest) expectedRequest).getEntity(); if (expectedEntity != null) { HttpEntity actualEntity = ((HttpEntityEnclosingRequest) actualRequest).getEntity(); assertEquals(EntityUtils.toString(expectedEntity), EntityUtils.toString(actualEntity)); } } } }
From source file:org.jenkinsci.plugins.GitLabSecurityRealm.java
/** * Returns the proxy to be used when connecting to the given URI. *///from w w w.j a va 2 s. c o m private HttpHost getProxy(HttpUriRequest method) throws URIException { Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { return null; // defensive check } ProxyConfiguration proxy = jenkins.proxy; if (proxy == null) { return null; // defensive check } Proxy p = proxy.createProxy(method.getURI().getHost()); switch (p.type()) { case DIRECT: return null; // no proxy case HTTP: InetSocketAddress sa = (InetSocketAddress) p.address(); return new HttpHost(sa.getHostName(), sa.getPort()); case SOCKS: default: return null; // not supported yet } }
From source file:com.siddroid.offlinews.SendOffline.java
/** * Fetch response./*from w w w.j a v a 2 s . c o m*/ * This function executes request. * @param request the request * @param client the client * @return the input stream */ private InputStream fetchResponse(HttpUriRequest request, DefaultHttpClient client) { try { Log.d("CHECK", ("executing request " + request.getRequestLine())); /*execute request and get response*/ HttpResponse getResponse = client.execute(request); final int statusCode = getResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.d(getClass().getSimpleName(), "Error " + statusCode + " for URL " + request.getURI()); return null; } HttpEntity getResponseEntity = getResponse.getEntity(); /*return response inputstream*/ return getResponseEntity.getContent(); } catch (IOException e) { request.abort(); } return null; }
From source file:com.soundcloud.playerapi.ApiWrapper.java
protected HttpHost determineTarget(HttpUriRequest request) { // A null target may be acceptable if there is a default target. // Otherwise, the null target is detected in the director. URI requestURI = request.getURI(); if (requestURI.isAbsolute()) { return new HttpHost(requestURI.getHost(), requestURI.getPort(), requestURI.getScheme()); } else {/* w w w . j a v a 2s.c o m*/ return null; } }
From source file:com.is.rest.cache.CacheAwareHttpClient.java
/** * Intercepts all requests sent and run them through the cache policies * @see AsyncHttpClient#sendRequest(org.apache.http.impl.client.DefaultHttpClient, org.apache.http.protocol.HttpContext, org.apache.http.client.methods.HttpUriRequest, String, ResponseHandlerInterface, Context) *//* www . j a va2 s . c o m*/ @Override @SuppressWarnings("unchecked") protected RequestHandle sendRequest(final DefaultHttpClient client, final HttpContext httpContext, final HttpUriRequest uriRequest, final String contentType, final ResponseHandlerInterface responseHandler, final Context context) { Logger.d("CacheAwareHttpClient.sendRequest"); AsyncTask<Void, Void, Pair<Object, Boolean>> task; if (Callback.class.isAssignableFrom(responseHandler.getClass())) { final Callback<Object> callback = (Callback<Object>) responseHandler; final CacheInfo cacheInfo = callback.getCacheInfo(); callback.setCacheManager(cacheManager); if (callback.getCacheInfo().getKey() == null) { try { callback.getCacheInfo().setKey(uriRequest.getURI().toURL().toString()); } catch (MalformedURLException e) { Logger.e("unchacheable because uri threw : ", e); } } task = new AsyncTask<Void, Void, Pair<Object, Boolean>>() { @Override public Pair<Object, Boolean> doInBackground(Void... params) { Pair<Object, Boolean> cachedResult = null; if (Callback.class.isAssignableFrom(responseHandler.getClass())) { switch (callback.getCacheInfo().getPolicy()) { case ENABLED: try { cachedResult = new Pair<Object, Boolean>( cacheManager.get(cacheInfo.getKey(), cacheInfo), false); } catch (IOException e) { Logger.e("cache error", e); } catch (ClassNotFoundException e) { Logger.e("cache error", e); } break; case NETWORK_ENABLED: try { cachedResult = new Pair<Object, Boolean>( cacheManager.get(cacheInfo.getKey(), cacheInfo), true); } catch (IOException e) { Logger.e("cache error", e); } catch (ClassNotFoundException e) { Logger.e("cache error", e); } break; case LOAD_IF_OFFLINE: if (callback.getContext() == null) { throw new IllegalArgumentException( "Attempt to use LOAD_IF_OFFLINE on a callback with no context provided. Context is required to lookup internet connectivity"); } ConnectivityManager connectivityManager = (ConnectivityManager) callback.getContext() .getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected()) { try { cachedResult = new Pair<Object, Boolean>( cacheManager.get(cacheInfo.getKey(), cacheInfo), false); } catch (IOException e) { Logger.e("cache error", e); } catch (ClassNotFoundException e) { Logger.e("cache error", e); } } break; default: break; } } return cachedResult; } @Override public void onPostExecute(Pair<Object, Boolean> result) { if (result != null && result.first != null) { Logger.d("CacheAwareHttpClient.sendRequest.onPostExecute proceeding with cache: " + result); callback.getCacheInfo().setLoadedFromCache(true); callback.onSuccess(HttpStatus.SC_OK, null, null, result.first); if (result.second != null && result.second) { //retry request if necessary even if loaded from cache such as in NETWORK_ENABLED if (Callback.class.isAssignableFrom(responseHandler.getClass())) { Callback<Object> callback = (Callback<Object>) responseHandler; CacheInfo secondCacheInfo = callback.getCacheInfo(); secondCacheInfo.setPolicy(CachePolicy.ENABLED); secondCacheInfo.setLoadedFromCache(false); try { boolean invalidated = cacheManager.invalidate(secondCacheInfo.getKey()); Logger.d(String.format("Key: '%s' invalidated as result of second call: %s", secondCacheInfo.getKey(), invalidated)); } catch (IOException e) { Logger.e("cache error", e); } Logger.d("Sending second cache filling call for " + uriRequest); CacheAwareHttpClient.super.sendRequest(client, httpContext, uriRequest, contentType, responseHandler, context); } } } else { Logger.d("CacheAwareHttpClient.sendRequest.onPostExecute proceeding uncached"); CacheAwareHttpClient.super.sendRequest(client, httpContext, uriRequest, contentType, responseHandler, context); } } }; ExecutionUtils.execute(task); } return new RequestHandle(null); }
From source file:net.ben.subsonic.androidapp.service.RESTMusicService.java
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); String redirectedUrl = host.toURI() + request.getURI(); redirectFrom = originalUrl.substring(0, originalUrl.indexOf("/rest/")); redirectTo = redirectedUrl.substring(0, redirectedUrl.indexOf("/rest/")); Log.i(TAG, redirectFrom + " redirects to " + redirectTo); redirectionLastChecked = System.currentTimeMillis(); redirectionNetworkType = getCurrentNetworkType(context); }
From source file:org.dataconservancy.dcs.ingest.client.impl.SwordClientManager.java
private DepositInfo execute(HttpUriRequest method) { try {//from w w w . ja v a 2 s . co m HttpResponse response = client.execute(method); int code = response.getStatusLine().getStatusCode(); if (code >= 200 && code <= 202) { Header[] headers = response.getAllHeaders(); InputStream content = response.getEntity().getContent(); byte[] body; try { body = IOUtils.toByteArray(content); } finally { content.close(); } if (response.containsHeader("Location")) { return new DcsDepositInfo(client, response.getFirstHeader("Location").getValue(), headers, body); } else { return new DcsDepositInfo(client, method.getURI().toASCIIString(), headers, body); } } else { log.warn(IOUtils.toString(response.getEntity().getContent())); throw new RuntimeException(String.format("Unexpected http code for %s: %s %s", method.getRequestLine(), code, response.getStatusLine().getReasonPhrase())); } } catch (IOException e) { throw new RuntimeException(e); } }
From source file:org.ambraproject.wombat.service.remote.AbstractRemoteService.java
@Override public CloseableHttpResponse getResponse(HttpUriRequest target) throws IOException { // Don't close the client, as this shuts down the connection pool. Do close every response or its entity stream. CloseableHttpClient client = createClient(); // We want to return an unclosed response, so close the response only if we throw an exception. boolean returningResponse = false; CloseableHttpResponse response = null; try {/* www .ja v a 2 s .co m*/ try { response = client.execute(target); } catch (HttpHostConnectException e) { throw new ServiceConnectionException(e); } StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (isErrorStatus(statusCode)) { URI targetUri = target.getURI(); String address = targetUri.getPath(); if (!Strings.isNullOrEmpty(targetUri.getQuery())) { address += "?" + targetUri.getQuery(); } if (statusCode == HttpStatus.NOT_FOUND.value()) { throw new EntityNotFoundException(address); } else { String responseBody = IOUtils.toString(response.getEntity().getContent()); String message = String.format("Request to \"%s\" failed (%d): %s.", address, statusCode, statusLine.getReasonPhrase()); throw new ServiceRequestException(statusCode, message, responseBody); } } returningResponse = true; return response; } finally { if (!returningResponse && response != null) { response.close(); } } }
From source file:bixo.fetcher.SimpleHttpFetcher.java
private String extractRedirectedUrl(String url, HttpContext localContext) { // This was triggered by HttpClient with the redirect count was exceeded. HttpHost host = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest finalRequest = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST); try {//from w ww . ja v a 2 s.c o m URL hostUrl = new URI(host.toURI()).toURL(); return new URL(hostUrl, finalRequest.getURI().toString()).toExternalForm(); } catch (MalformedURLException e) { LOGGER.warn("Invalid host/uri specified in final fetch: " + host + finalRequest.getURI()); return url; } catch (URISyntaxException e) { LOGGER.warn("Invalid host/uri specified in final fetch: " + host + finalRequest.getURI()); return url; } }
From source file:org.fcrepo.apix.jena.impl.JenaServiceRegistry.java
private CloseableHttpResponse execute(final HttpUriRequest req) throws Exception { final CloseableHttpResponse resp = client.execute(req); final int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode < 200 || statusCode >= 300) { String body;//from www. j a v a2s .c o m try { body = EntityUtils.toString(resp.getEntity()); } catch (final IOException e) { body = e.getMessage(); } throw new RuntimeException(String.format("Unexpected status code %s when interacting wirth <%s>: %s", statusCode, req.getURI(), body)); } return resp; }