List of usage examples for org.apache.http.client.methods HttpRequestBase getURI
public URI getURI()
From source file:com.alu.e3.gateway.loadbalancer.HttpLoadBalancerProducer.java
protected HttpRequestBase createMethod(Exchange exchange) throws URISyntaxException, CamelExchangeException { HttpRequestBase httpRequest = super.createMethod(exchange); HttpParams params = httpRequest.getParams(); Integer connectionTimeout = exchange.getProperty(ExchangeConstantKeys.E3_HTTP_CONNECTION_TIMEOUT.toString(), E3Constant.DEFAULT_HTTP_CONNECTION_TIMETOUT, Integer.class); Integer socketTimeout = exchange.getProperty(ExchangeConstantKeys.E3_HTTP_SOCKET_TIMEOUT.toString(), E3Constant.DEFAULT_HTTP_SOCKET_TIMEOUT, Integer.class); HttpConnectionParamBean httpConnectionParamBean = new HttpConnectionParamBean(params); httpConnectionParamBean.setConnectionTimeout(connectionTimeout); httpConnectionParamBean.setSoTimeout(socketTimeout); exchange.getIn().setHeader(HttpHeaders.HOST, httpRequest.getURI().getHost()); return httpRequest; }
From source file:com.ibm.watson.developer_cloud.service.WatsonService.java
/** * Execute the Http request./*from w ww .j av a2 s.co m*/ * * @param request * the http request * * @return the http response */ protected HttpResponse execute(HttpRequestBase request) { setAuthentication(request); if (getEndPoint() == null) throw new IllegalArgumentException("service endpoint was not specified"); if (!request.containsHeader(ACCEPT)) { request.addHeader(ACCEPT, getDefaultContentType()); } // from /v1/foo/bar to https://host:port/api/v1/foo/bar if (!request.getURI().isAbsolute()) { request.setURI(buildRequestURI(request)); } HttpResponse response; //HttpHost proxy=new HttpHost("10.100.1.124",3128); log.log(Level.FINEST, "Request to: " + request.getURI()); try { response = getHttpClient().execute(request); //ConnRouteParams.setDefaultProxy(response.getParams(),proxy); } catch (ClientProtocolException e) { log.log(Level.SEVERE, "ClientProtocolException", e); throw new RuntimeException(e); } catch (IOException e) { log.log(Level.SEVERE, "IOException", e); throw new RuntimeException(e); } final int status = response.getStatusLine().getStatusCode(); log.log(Level.FINEST, "Response HTTP Status: " + status); if (status >= 200 && status < 300) return response; // There was a Client Error 4xx or a Server Error 5xx // Get the error message and create the exception String error = getErrorMessage(response); log.log(Level.SEVERE, "HTTP Status: " + status + ", message: " + error); switch (status) { case HttpStatus.SC_BAD_REQUEST: // HTTP 400 throw new BadRequestException(error != null ? error : "Bad Request"); case HttpStatus.SC_UNAUTHORIZED: // HTTP 401 throw new UnauthorizedException("Unauthorized: Access is denied due to invalid credentials"); case HttpStatus.SC_FORBIDDEN: // HTTP 403 throw new ForbiddenException(error != null ? error : "Forbidden: Service refuse the request"); case HttpStatus.SC_NOT_FOUND: // HTTP 404 throw new NotFoundException(error != null ? error : "Not found"); case HttpStatus.SC_NOT_ACCEPTABLE: // HTTP 406 throw new ForbiddenException(error != null ? error : "Forbidden: Service refuse the request"); case HttpStatus.SC_REQUEST_TOO_LONG: // HTTP 413 throw new RequestTooLargeException(error != null ? error : "Request too large: The request entity is larger than the server is able to process"); case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE: // HTTP 415 throw new UnsupportedException(error != null ? error : "Unsupported MIME type: The request entity has a media type which the server or resource does not support"); case 429: // HTTP 429 throw new TooManyRequestsException(error != null ? error : "Too many requests"); case HttpStatus.SC_INTERNAL_SERVER_ERROR: // HTTP 500 throw new InternalServerErrorException(error != null ? error : "Internal Server Error"); case HttpStatus.SC_SERVICE_UNAVAILABLE: // HTTP 503 throw new ServiceUnavailableException(error != null ? error : "Service Unavailable"); default: // other errors throw new ServiceResponseException(status, error); } }
From source file:org.xwiki.wysiwyg.internal.plugin.alfresco.server.TicketAuthenticator.java
@Override public void authenticate(HttpRequestBase request) { String ticket = null;/*from w w w.ja v a 2 s. c o m*/ //get ticket from DB AlfrescoTiket dbTiket = ticketManager.getTicket(); //if there is a ticket for current user,use it if (dbTiket != null) { ticket = dbTiket.getTiket(); } /*if (ticket != null) { if (!ticketManager.validateAuthenticationTicket(ticket)) { //if ticket is not valid on alfresco, perform authentication ticket = getAuthenticationTicket(); } } else { //if there is no ticket in DB, perform authentication ticket = getAuthenticationTicket(); }*/ // Add the ticket to the query string. URI uri = request.getURI(); List<NameValuePair> parameters = URLEncodedUtils.parse(uri, QUERY_STRING_ENCODING); parameters.add(new BasicNameValuePair(AUTH_TICKET_PARAM, ticket)); String query = URLEncodedUtils.format(parameters, QUERY_STRING_ENCODING); try { request.setURI(URIUtils.createURI(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getRawPath(), query, uri.getRawFragment())); } catch (URISyntaxException e) { // This shouldn't happen. } }
From source file:org.fao.geonet.utils.AbstractHttpRequest.java
protected ClientHttpResponse doExecute(final HttpRequestBase httpMethod) throws IOException { return requestFactory.execute(httpMethod, new Function<HttpClientBuilder, Void>() { @Nullable// w w w .j a v a 2 s . c om @Override public Void apply(@Nonnull HttpClientBuilder input) { final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); if (credentials != null) { final URI uri = httpMethod.getURI(); HttpHost hh = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); credentialsProvider.setCredentials(new AuthScope(hh), credentials); // Preemptive authentication if (isPreemptiveBasicAuth()) { // 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(hh, basicAuth); // Add AuthCache to the execution context httpClientContext = HttpClientContext.create(); httpClientContext.setCredentialsProvider(credentialsProvider); httpClientContext.setAuthCache(authCache); } else { input.setDefaultCredentialsProvider(credentialsProvider); } } else { input.setDefaultCredentialsProvider(credentialsProvider); } if (useProxy) { final HttpHost proxy = new HttpHost(proxyHost, proxyPort); input.setProxy(proxy); if (proxyCredentials != null) { credentialsProvider.setCredentials(new AuthScope(proxy), proxyCredentials); } } input.setRedirectStrategy(new LaxRedirectStrategy()); return null; } }, this); }
From source file:org.sonatype.nexus.repository.proxy.ProxyFacetSupport.java
/** * Extract Last-Modified date from response if possible, or {@code null}. *//*from w w w . ja v a 2 s . co m*/ @Nullable private DateTime extractLastModified(final HttpRequestBase request, final HttpResponse response) { final Header lastModifiedHeader = response.getLastHeader(HttpHeaders.LAST_MODIFIED); if (lastModifiedHeader != null) { try { return new DateTime(DateUtils.parseDate(lastModifiedHeader.getValue()).getTime()); } catch (Exception ex) { log.warn( "Could not parse date '{}' received from {}; using system current time as item creation time", lastModifiedHeader, request.getURI()); } } return null; }
From source file:com.gsma.mobileconnect.utils.RestClient.java
/** * Execute the given request./*from w w w . j a va 2 s.c o m*/ * <p> * Abort the request if it exceeds the specified timeout. * * @param httpClient The client to use. * @param request The request to make. * @param context The context to use. * @param timeout The timeout to use. * @return A Http Response. * @throws RestException Thrown if the request fails or times out. */ private CloseableHttpResponse executeRequest(CloseableHttpClient httpClient, final HttpRequestBase request, HttpClientContext context, int timeout) throws RestException { Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { request.abort(); } }, timeout); RequestConfig localConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout) .setConnectTimeout(timeout).setSocketTimeout(timeout).setCookieSpec(CookieSpecs.STANDARD).build(); request.setConfig(localConfig); try { return httpClient.execute(request, context); } catch (IOException ex) { String requestUri = request.getURI().toString(); if (request.isAborted()) { throw new RestException("Rest end point did not respond", requestUri); } throw new RestException("Rest call failed", requestUri, ex); } }
From source file:org.hyperic.hq.plugin.jboss7.JBossAdminHttp.java
private Object query(HttpRequestBase req, String api, Type type) throws PluginException { Object res = null;//from w w w . j a v a 2s . c o m try { HttpResponse response = client.execute(req, localcontext); int statusCode = response.getStatusLine().getStatusCode(); // response must be read in order to "close" the connection. // https://jira.hyperic.com/browse/HHQ-5063#comment-154101 String responseBody = readInputString(response.getEntity().getContent()); if (log.isDebugEnabled()) { log.debug("[" + api + "] -(" + req.getURI() + ")-> " + responseBody); } if (statusCode != 200) { throw new PluginException("[" + req.getURI() + "] http error code: '" + statusCode + "' msg='" + response.getStatusLine().getReasonPhrase() + "'"); } GsonBuilder gsb = new GsonBuilder(); if (!((type instanceof Class) && ((Class) type).getCanonicalName().equals(Connector.class.getCanonicalName()))) { gsb.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES); } Gson gson = gsb.create(); res = gson.fromJson(responseBody, type); if (log.isDebugEnabled()) { if (res.getClass().isArray()) { log.debug("[" + api + "] -(" + statusCode + ")*> " + Arrays.asList((Object[]) res)); } else { log.debug("[" + api + "] -(" + statusCode + ")-> " + res); } } } catch (JsonParseException ex) { log.debug(ex.getMessage(), ex); throw new PluginException(ex.getMessage(), ex); } catch (IOException ex) { log.debug(ex.getMessage(), ex); throw new PluginException(ex.getMessage(), ex); } return res; }
From source file:org.niord.core.keycloak.KeycloakIntegrationService.java
/** * Executes a Keycloak admin request and returns the result. * * @param request the Keycloak request to execute * @param auth whether to add a Bearer authorization header or not * @param responseHandler the response handler * @return the result// w ww . j a v a2 s . co m */ private <R> R executeAdminRequest(HttpRequestBase request, boolean auth, KeycloakResponseHandler<R> responseHandler) throws Exception { if (auth) { KeycloakPrincipal keycloakPrincipal = userService.getCallerPrincipal(); if (keycloakPrincipal == null) { throw new Exception("Unable to execute request " + request.getURI() + ". User not authenticated"); } request.addHeader("Authorization", "Bearer " + keycloakPrincipal.getKeycloakSecurityContext().getTokenString()); } // TODO: Check if this works with https based on self-signed certificates HttpClient client = HttpClients.custom().setHostnameVerifier(new AllowAllHostnameVerifier()).build(); HttpResponse response = client.execute(request); int status = response.getStatusLine().getStatusCode(); if (status < 200 || status > 299) { try { response.getEntity().getContent().close(); } catch (Exception ignored) { } throw new Exception("Unable to execute request " + request.getURI() + ", status = " + status); } HttpEntity entity = response.getEntity(); if (entity == null) { return responseHandler.execute(null); } try (InputStream is = entity.getContent()) { return responseHandler.execute(is); } }