List of usage examples for org.apache.http.client.methods HttpRequestBase setConfig
public void setConfig(final RequestConfig config)
From source file:com.agileapes.couteau.http.client.impl.DefaultLatentHttpClient.java
private HttpRequestBase getRequest(HttpRequest httpRequest) throws BeanInstantiationException { final HttpRequestBase request = initializer.initialize(httpRequest.getMethod().getRequestType(), new Class[0]); request.setURI(httpRequest.getURI()); if (httpRequest.getConfig() != null) { request.setConfig(httpRequest.getConfig()); } else {// w w w.j a v a 2 s. co m request.setConfig(config); } for (HttpHeader header : httpRequest.getHeaders()) { request.setHeader(header.getName(), header.getValue()); } if (request instanceof HttpEntityEnclosingRequest) { ((HttpEntityEnclosingRequest) request).setEntity(httpRequest.getData()); } return request; }
From source file:org.metaeffekt.dcc.agent.DeploymentBasedEndpointUriBuilder.java
public HttpUriRequest buildHttpUriRequest(Commands command, Id<DeploymentId> deploymentId, HttpEntity payload) { StringBuilder sb = new StringBuilder("/"); sb.append(PATH_ROOT).append("/"); sb.append(deploymentId).append("/"); sb.append(command);//w ww . j a va 2s . c om String path = sb.toString(); URIBuilder uriBuilder = createUriBuilder(); uriBuilder.setPath(path); URI uri; try { uri = uriBuilder.build(); } catch (URISyntaxException e) { throw new RuntimeException(e); } HttpRequestBase request; if (HTTP_PUT.equals(determineHttpMethod(command))) { request = new HttpPut(uri); if (payload != null) { ((HttpPut) request).setEntity(payload); } } else { request = new HttpGet(uri); } if (requestConfig != null) { request.setConfig(requestConfig); } return request; }
From source file:com.comcast.drivethru.client.DefaultRestClient.java
@Override public RestResponse execute(RestRequest request) throws HttpException { /* Build the URL String */ String url = request.getUrl().setDefaultBaseUrl(defaultBaseUrl).build(); /* Get our Apache RestRequest object */ Method method = request.getMethod(); HttpRequestBase req = method.getRequest(url); req.setConfig(request.getConfig()); /* Add the Body */ byte[] payload = request.getBody(); if (null != payload) { if (req instanceof HttpEntityEnclosingRequest) { HttpEntity entity = new ByteArrayEntity(payload); ((HttpEntityEnclosingRequest) req).setEntity(entity); } else {// www . j av a 2s . c om throw new HttpException("Cannot attach a body to a " + method.name() + " request"); } } /* Add all Headers */ for (Entry<String, String> pair : defaultHeaders.entrySet()) { req.addHeader(pair.getKey(), pair.getValue()); } for (Entry<String, String> pair : request.getHeaders().entrySet()) { req.addHeader(pair.getKey(), pair.getValue()); } /* If there is a security provider, sign */ if (null != securityProvider) { securityProvider.sign(req); } /* Closed in the finally block */ InputStream in = null; ByteArrayOutputStream baos = null; try { /* Finally, execute the thing */ org.apache.http.HttpResponse resp = delegate.execute(req); /* Create our response */ RestResponse response = new RestResponse(resp.getStatusLine()); /* Add all Headers */ response.addAll(resp.getAllHeaders()); /* Add the content */ HttpEntity body = resp.getEntity(); if (null != body) { in = body.getContent(); baos = new ByteArrayOutputStream(); IOUtils.copy(in, baos); response.setBody(baos.toByteArray()); } return response; } catch (RuntimeException ex) { // release resources immediately req.abort(); throw ex; } catch (HttpResponseException hrex) { throw new HttpStatusException(hrex.getStatusCode()); } catch (ClientProtocolException cpex) { throw new HttpException("HTTP Protocol error occurred.", cpex); } catch (IOException ioex) { throw new HttpException("Error establishing connection.", ioex); } finally { req.abort(); IOUtils.closeQuietly(in); IOUtils.closeQuietly(baos); } }
From source file:com.shenit.commons.utils.HttpUtils.java
/** * Request url result with get method/*from w ww.j a va 2s . c om*/ * * @param request * @param context * @param proxy * @param cTimeout * @param soTimeout * @return */ public static String execute(HttpRequestBase request, HttpContext context, HttpHost proxy, int cTimeout, int soTimeout) { RequestConfig config = RequestConfig.custom().setConnectTimeout(cTimeout) .setConnectionRequestTimeout(soTimeout).build(); request.setConfig(config); String result = null; CloseableHttpClient client = HttpClientBuilder.create().setProxy(proxy).build(); try { if (LOG.isDebugEnabled()) LOG.debug("[execute] request -> \n>>>>>>>>>>>>>>>>\n{}\n<<<<<<<<<<<<<<<<\n", dumpRequest(request)); HttpResponse resp = client.execute(request, context); result = EntityUtils.toString(resp.getEntity(), getContentEncoding(resp)); if (LOG.isDebugEnabled()) LOG.debug("[execute] response -> \n>>>>>>>>>>>>>>>>\n{}\n<<<<<<<<<<<<<<<<\n", result); } catch (ClientProtocolException e) { LOG.warn("[execute]Error when calling url >> " + request.getURI(), e); } catch (IOException e) { LOG.warn("[execute]IOException when calling url >> " + request.getURI(), e); } return result; }
From source file:com.wudaosoft.net.httpclient.ParameterRequestBuilder.java
public static HttpUriRequest build(RequestBuilder builder) { final HttpRequestBase result; URI uriNotNull = builder.getUri() != null ? builder.getUri() : URI.create("/"); Charset charset = builder.getCharset(); charset = charset != null ? charset : HTTP.DEF_CONTENT_CHARSET; String method = builder.getMethod(); List<NameValuePair> parameters = builder.getParameters(); HttpEntity entityCopy = builder.getEntity(); if (parameters != null && !parameters.isEmpty()) { if (entityCopy == null && (HttpPost.METHOD_NAME.equalsIgnoreCase(method) || HttpPut.METHOD_NAME.equalsIgnoreCase(method) || HttpPatch.METHOD_NAME.equalsIgnoreCase(method))) { entityCopy = new UrlEncodedFormEntity(parameters, charset); } else {/* w w w .ja v a 2 s .com*/ try { uriNotNull = new URIBuilder(uriNotNull).setCharset(charset).addParameters(parameters).build(); } catch (final URISyntaxException ex) { // should never happen } } } if (entityCopy == null) { result = new InternalRequest(method); } else { final InternalEntityEclosingRequest request = new InternalEntityEclosingRequest(method); request.setEntity(entityCopy); result = request; } result.setProtocolVersion(builder.getVersion()); result.setURI(uriNotNull); // if (builder.headergroup != null) { // result.setHeaders(builder.headergroup.getAllHeaders()); // } result.setConfig(builder.getConfig()); return result; }
From source file:com.gsma.mobileconnect.utils.RestClient.java
/** * Execute the given request./*from w w w .j a v a 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.nextlets.erc.defaults.http.ERCHttpInvokerImpl.java
protected void addProxy(ERCConfiguration configuration, HttpRequestBase req) { if (configuration.getProxyUrl() != null && !configuration.getProxyUrl().isEmpty()) { log.debug("Proxy: {}", configuration.getProxyUrl()); URI proxyUri;/*from w ww . j a v a2 s . c om*/ try { proxyUri = new URI(configuration.getProxyUrl()); } catch (URISyntaxException ex) { throw new ERCClientException(ex); } HttpHost proxy = new HttpHost(proxyUri.getHost(), proxyUri.getPort(), proxyUri.getScheme()); req.setConfig(RequestConfig.custom().setProxy(proxy).build()); } }
From source file:com.smartling.api.sdk.util.HttpUtils.java
/** * Method for executing http calls and retrieving string response. * @param httpRequest request for execute * @param proxyConfiguration proxy configuration, if it is set to {@code NULL} proxy settings will be setup from system properties. Otherwise switched off. * @return {@link StringResponse} the contents of the requested file along with the encoding of the file. * @throws com.smartling.api.sdk.exceptions.SmartlingApiException if an exception has occurred or non success is returned from the Smartling Translation API. *//*from ww w .ja v a 2 s . c o m*/ public StringResponse executeHttpCall(final HttpRequestBase httpRequest, final ProxyConfiguration proxyConfiguration) throws SmartlingApiException { CloseableHttpClient httpClient = null; try { requestId.remove(); responseDetails.remove(); ProxyConfiguration newProxyConfiguration = mergeSystemProxyConfiguration(proxyConfiguration); logProxyConfiguration(newProxyConfiguration); httpClient = httpProxyUtils.getHttpClient(newProxyConfiguration); RequestConfig proxyRequestConfig = httpProxyUtils.getProxyRequestConfig(httpRequest, newProxyConfiguration); if (proxyRequestConfig != null) { httpRequest.setConfig(proxyRequestConfig); } addUserAgentHeader(httpRequest); final HttpResponse response = httpClient.execute(httpRequest); final String charset = EntityUtils.getContentCharSet(response.getEntity()); int statusCode = response.getStatusLine().getStatusCode(); Header header = response.getFirstHeader(X_SL_REQUEST_ID); if (header != null) { requestId.set(header.getValue()); } ResponseDetails details = new ResponseDetails(statusCode, response.getAllHeaders()); responseDetails.set(details); return inputStreamToString(response.getEntity().getContent(), charset, statusCode); } catch (final IOException ioe) { logger.error(String.format(LOG_MESSAGE_ERROR_TEMPLATE, ioe.getMessage())); throw new SmartlingApiException(ioe); } finally { try { if (null != httpClient) httpClient.close(); } catch (final IOException ioe) { logger.warn(String.format(LOG_MESSAGE_ERROR_TEMPLATE, ioe.getMessage())); } } }
From source file:org.elasticsearch.xpack.security.authc.saml.SamlAuthenticationIT.java
private <T> T execute(CloseableHttpClient client, HttpRequestBase request, HttpContext context, CheckedFunction<HttpResponse, T, IOException> body) throws IOException { final int timeout = (int) TimeValue.timeValueSeconds(90).millis(); RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout) .setConnectTimeout(timeout).setSocketTimeout(timeout).build(); request.setConfig(requestConfig); logger.info("Execute HTTP " + request.getMethod() + ' ' + request.getURI()); try (CloseableHttpResponse response = SocketAccess.doPrivileged(() -> client.execute(request, context))) { return body.apply(response); } catch (Exception e) { logger.warn(new ParameterizedMessage("HTTP Request [{}] failed", request.getURI()), e); throw e;/*from w w w . j av a 2 s . com*/ } }
From source file:com.seleritycorp.common.base.http.client.HttpRequest.java
private org.apache.http.HttpResponse getHttpResponse() throws HttpException { final HttpRequestBase request; switch (method) { case HttpGet.METHOD_NAME: request = new HttpGet(); break;//from w ww .j av a 2 s . c om case HttpPost.METHOD_NAME: request = new HttpPost(); break; default: throw new HttpException("Unknown HTTP method '" + method + "'"); } try { request.setURI(URI.create(uri)); } catch (IllegalArgumentException e) { throw new HttpException("Failed to create URI '" + uri + "'", e); } if (userAgent != null) { request.setHeader(HTTP.USER_AGENT, userAgent); } if (readTimeoutMillis >= 0) { request.setConfig(RequestConfig.custom().setSocketTimeout(readTimeoutMillis) .setConnectTimeout(readTimeoutMillis).setConnectionRequestTimeout(readTimeoutMillis).build()); } if (!data.isEmpty()) { if (request instanceof HttpEntityEnclosingRequestBase) { final HttpEntity entity; ContentType localContentType = contentType; if (localContentType == null) { localContentType = ContentType.create("text/plain", StandardCharsets.UTF_8); } entity = new StringEntity(data, localContentType); HttpEntityEnclosingRequestBase entityRequest = (HttpEntityEnclosingRequestBase) request; entityRequest.setEntity(entity); } else { throw new HttpException( "Request " + request.getMethod() + " does not allow to send data " + "with the request"); } } final HttpClient httpClient; if (uri.startsWith("file://")) { httpClient = this.fileHttpClient; } else { httpClient = this.netHttpClient; } final org.apache.http.HttpResponse response; try { response = httpClient.execute(request); } catch (IOException e) { throw new HttpException("Failed to execute request to '" + uri + "'", e); } return response; }