List of usage examples for org.apache.http.client.methods HttpRequestBase addHeader
public void addHeader(String str, String str2)
From source file:com.sun.identity.proxy.client.ClientHandler.java
/** * Submits the exchange request to the remote server. Creates and * populates the exchange response from that provided by the remote server. *///ww w .java 2 s.c o m @Override public void handle(Exchange exchange) throws IOException, HandlerException { // recover any previous response connection, if present if (exchange.response != null && exchange.response.entity != null) { exchange.response.entity.close(); } HttpRequestBase clientRequest = (exchange.request.entity != null ? new EntityRequest(exchange.request) : new NonEntityRequest(exchange.request)); clientRequest.setURI(exchange.request.uri); // connection headers to suppress CIStringSet suppressConnection = new CIStringSet(); // parse request connection headers to be treated as hop-to-hop suppressConnection.clear(); suppressConnection.addAll(getConnectionHeaders(exchange.request.headers)); // request headers for (String name : exchange.request.headers.keySet()) { if (!SUPPRESS_REQUEST_HEADERS.contains(name) && !suppressConnection.contains(name)) { for (String value : exchange.request.headers.get(name)) { clientRequest.addHeader(name, value); } } } HttpResponse clientResponse = httpClient.execute(clientRequest); exchange.response = new Response(); // response entity HttpEntity clientResponseEntity = clientResponse.getEntity(); if (clientResponseEntity != null) { exchange.response.entity = clientResponseEntity.getContent(); } // response status line StatusLine statusLine = clientResponse.getStatusLine(); exchange.response.version = statusLine.getProtocolVersion().toString(); exchange.response.status = statusLine.getStatusCode(); exchange.response.reason = statusLine.getReasonPhrase(); // parse response connection headers to be suppressed in response suppressConnection.clear(); suppressConnection.addAll(getConnectionHeaders(exchange.response.headers)); // response headers for (HeaderIterator i = clientResponse.headerIterator(); i.hasNext();) { Header header = i.nextHeader(); String name = header.getName(); if (!SUPPRESS_RESPONSE_HEADERS.contains(name) && !suppressConnection.contains(name)) { exchange.response.headers.add(name, header.getValue()); } } // TODO: decide if need to try-finally to call httpRequest.abort? }
From source file:com.sat.vcse.automation.utils.http.HttpClient.java
/** * adds header values in http method object * @param httpMethod//from w ww. j ava 2 s . c o m */ private void addHeader(final HttpRequestBase httpMethod) { // Build the HTTP request header from the HeadersMap for (Map.Entry<String, String> entry : this.requestHeaders.entrySet()) { httpMethod.addHeader(entry.getKey(), entry.getValue()); } }
From source file:cn.ctyun.amazonaws.http.HttpRequestFactory.java
/** Configures the headers in the specified Apache HTTP request. */ private void configureHeaders(HttpRequestBase httpRequest, Request<?> request, ExecutionContext context, ClientConfiguration clientConfiguration) { /*/*from w ww.j a v a 2 s.c om*/ * Apache HttpClient omits the port number in the Host header (even if * we explicitly specify it) if it's the default port for the protocol * in use. To ensure that we use the same Host header in the request and * in the calculated string to sign (even if Apache HttpClient changed * and started honoring our explicit host with endpoint), we follow this * same behavior here and in the QueryString signer. */ URI endpoint = request.getEndpoint(); String hostHeader = endpoint.getHost(); if (HttpUtils.isUsingNonDefaultPort(endpoint)) { hostHeader += ":" + endpoint.getPort(); } httpRequest.addHeader("Host", hostHeader); // Copy over any other headers already in our request for (Entry<String, String> entry : request.getHeaders().entrySet()) { /* * HttpClient4 fills in the Content-Length header and complains if * it's already present, so we skip it here. We also skip the Host * header to avoid sending it twice, which will interfere with some * signing schemes. */ if (entry.getKey().equalsIgnoreCase("Content-Length") || entry.getKey().equalsIgnoreCase("Host")) continue; httpRequest.addHeader(entry.getKey(), entry.getValue()); } /* Set content type and encoding */ if (httpRequest.getHeaders("Content-Type") == null || httpRequest.getHeaders("Content-Type").length == 0) { httpRequest.addHeader("Content-Type", "application/x-www-form-urlencoded; " + "charset=" + DEFAULT_ENCODING.toLowerCase()); } // Override the user agent string specified in the client params if the context requires it if (context != null && context.getContextUserAgent() != null) { httpRequest.addHeader("User-Agent", createUserAgentString(clientConfiguration, context.getContextUserAgent())); } }
From source file:com.amazon.s3.http.HttpRequestFactory.java
/** Configures the headers in the specified Apache HTTP request. */ private void configureHeaders(HttpRequestBase httpRequest, Request<?> request, ExecutionContext context, ClientConfiguration clientConfiguration) { /*/*from ww w . j a v a 2 s.c o m*/ * Apache HttpClient omits the port number in the Host header (even if * we explicitly specify it) if it's the default port for the protocol * in use. To ensure that we use the same Host header in the request and * in the calculated string to sign (even if Apache HttpClient changed * and started honoring our explicit host with endpoint), we follow this * same behavior here and in the QueryString signer. */ URI endpoint = request.getEndpoint(); String hostHeader = endpoint.getHost(); if (HttpUtils.isUsingNonDefaultPort(endpoint)) { hostHeader += ":" + endpoint.getPort(); } httpRequest.addHeader("Host", hostHeader); // Copy over any other headers already in our request for (Entry<String, String> entry : request.getHeaders().entrySet()) { /* * HttpClient4 fills in the Content-Length header and complains if * it's already present, so we skip it here. We also skip the Host * header to avoid sending it twice, which will interfere with some * signing schemes. */ if (entry.getKey().equalsIgnoreCase("Content-Length") || entry.getKey().equalsIgnoreCase("Host")) continue; httpRequest.addHeader(entry.getKey(), entry.getValue()); } /* Set content type and encoding */ if (httpRequest.getHeaders("Content-Type") == null || httpRequest.getHeaders("Content-Type").length == 0) { httpRequest.addHeader("Content-Type", "application/x-www-form-urlencoded; " + "charset=" + DEFAULT_ENCODING.toLowerCase()); } // Override the user agent string specified in the client params if the // context requires it if (context != null && context.getContextUserAgent() != null) { httpRequest.addHeader("User-Agent", createUserAgentString(clientConfiguration, context.getContextUserAgent())); } }
From source file:com.clickntap.vimeo.Vimeo.java
private VimeoResponse apiRequest(String endpoint, String methodName, Map<String, String> params, File file) throws IOException { CloseableHttpClient client = HttpClientBuilder.create().build(); HttpRequestBase request = null; String url = null;/*from w w w . j a va 2s.com*/ if (endpoint.startsWith("http")) { url = endpoint; } else { url = new StringBuffer(VIMEO_SERVER).append(endpoint).toString(); } if (methodName.equals(HttpGet.METHOD_NAME)) { request = new HttpGet(url); } else if (methodName.equals(HttpPost.METHOD_NAME)) { request = new HttpPost(url); } else if (methodName.equals(HttpPut.METHOD_NAME)) { request = new HttpPut(url); } else if (methodName.equals(HttpDelete.METHOD_NAME)) { request = new HttpDelete(url); } else if (methodName.equals(HttpPatch.METHOD_NAME)) { request = new HttpPatch(url); } request.addHeader("Accept", "application/vnd.vimeo.*+json; version=3.2"); request.addHeader("Authorization", new StringBuffer(tokenType).append(" ").append(token).toString()); HttpEntity entity = null; if (params != null) { ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); for (String key : params.keySet()) { postParameters.add(new BasicNameValuePair(key, params.get(key))); } entity = new UrlEncodedFormEntity(postParameters); } else if (file != null) { entity = new FileEntity(file, ContentType.MULTIPART_FORM_DATA); } if (entity != null) { if (request instanceof HttpPost) { ((HttpPost) request).setEntity(entity); } else if (request instanceof HttpPatch) { ((HttpPatch) request).setEntity(entity); } else if (request instanceof HttpPut) { ((HttpPut) request).setEntity(entity); } } CloseableHttpResponse response = client.execute(request); String responseAsString = null; int statusCode = response.getStatusLine().getStatusCode(); if (methodName.equals(HttpPut.METHOD_NAME) || methodName.equals(HttpDelete.METHOD_NAME)) { JSONObject out = new JSONObject(); for (Header header : response.getAllHeaders()) { out.put(header.getName(), header.getValue()); } responseAsString = out.toString(); } else if (statusCode != 204) { ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); responseAsString = out.toString("UTF-8"); out.close(); } JSONObject json = null; try { json = new JSONObject(responseAsString); } catch (Exception e) { json = new JSONObject(); } VimeoResponse vimeoResponse = new VimeoResponse(json, statusCode); response.close(); client.close(); return vimeoResponse; }
From source file:org.apache.solr.client.solrj.impl.HttpSolrClient.java
protected NamedList<Object> executeMethod(HttpRequestBase method, final ResponseParser processor) throws SolrServerException { method.addHeader("User-Agent", AGENT); org.apache.http.client.config.RequestConfig.Builder requestConfigBuilder = HttpClientUtil .createDefaultRequestConfigBuilder(); if (soTimeout != null) { requestConfigBuilder.setSocketTimeout(soTimeout); }//www . j a va 2 s. c o m if (connectionTimeout != null) { requestConfigBuilder.setConnectTimeout(connectionTimeout); } if (followRedirects != null) { requestConfigBuilder.setRedirectsEnabled(followRedirects); } method.setConfig(requestConfigBuilder.build()); HttpEntity entity = null; InputStream respBody = null; boolean shouldClose = true; try { // Execute the method. HttpClientContext httpClientRequestContext = HttpClientUtil.createNewHttpClientRequestContext(); final HttpResponse response = httpClient.execute(method, httpClientRequestContext); int httpStatus = response.getStatusLine().getStatusCode(); // Read the contents entity = response.getEntity(); respBody = entity.getContent(); Header ctHeader = response.getLastHeader("content-type"); String contentType; if (ctHeader != null) { contentType = ctHeader.getValue(); } else { contentType = ""; } // handle some http level checks before trying to parse the response switch (httpStatus) { case HttpStatus.SC_OK: case HttpStatus.SC_BAD_REQUEST: case HttpStatus.SC_CONFLICT: // 409 break; case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_MOVED_TEMPORARILY: if (!followRedirects) { throw new SolrServerException( "Server at " + getBaseURL() + " sent back a redirect (" + httpStatus + ")."); } break; default: if (processor == null || "".equals(contentType)) { throw new RemoteSolrException(baseUrl, httpStatus, "non ok status: " + httpStatus + ", message:" + response.getStatusLine().getReasonPhrase(), null); } } if (processor == null || processor instanceof InputStreamResponseParser) { // no processor specified, return raw stream NamedList<Object> rsp = new NamedList<>(); rsp.add("stream", respBody); // Only case where stream should not be closed shouldClose = false; return rsp; } String procCt = processor.getContentType(); if (procCt != null) { String procMimeType = ContentType.parse(procCt).getMimeType().trim().toLowerCase(Locale.ROOT); String mimeType = ContentType.parse(contentType).getMimeType().trim().toLowerCase(Locale.ROOT); if (!procMimeType.equals(mimeType)) { // unexpected mime type String msg = "Expected mime type " + procMimeType + " but got " + mimeType + "."; Header encodingHeader = response.getEntity().getContentEncoding(); String encoding; if (encodingHeader != null) { encoding = encodingHeader.getValue(); } else { encoding = "UTF-8"; // try UTF-8 } try { msg = msg + " " + IOUtils.toString(respBody, encoding); } catch (IOException e) { throw new RemoteSolrException(baseUrl, httpStatus, "Could not parse response with encoding " + encoding, e); } throw new RemoteSolrException(baseUrl, httpStatus, msg, null); } } NamedList<Object> rsp = null; String charset = EntityUtils.getContentCharSet(response.getEntity()); try { rsp = processor.processResponse(respBody, charset); } catch (Exception e) { throw new RemoteSolrException(baseUrl, httpStatus, e.getMessage(), e); } if (httpStatus != HttpStatus.SC_OK) { NamedList<String> metadata = null; String reason = null; try { NamedList err = (NamedList) rsp.get("error"); if (err != null) { reason = (String) err.get("msg"); if (reason == null) { reason = (String) err.get("trace"); } metadata = (NamedList<String>) err.get("metadata"); } } catch (Exception ex) { } if (reason == null) { StringBuilder msg = new StringBuilder(); msg.append(response.getStatusLine().getReasonPhrase()).append("\n\n").append("request: ") .append(method.getURI()); reason = java.net.URLDecoder.decode(msg.toString(), UTF_8); } RemoteSolrException rss = new RemoteSolrException(baseUrl, httpStatus, reason, null); if (metadata != null) rss.setMetadata(metadata); throw rss; } return rsp; } catch (ConnectException e) { throw new SolrServerException("Server refused connection at: " + getBaseURL(), e); } catch (SocketTimeoutException e) { throw new SolrServerException("Timeout occured while waiting response from server at: " + getBaseURL(), e); } catch (IOException e) { throw new SolrServerException("IOException occured when talking to server at: " + getBaseURL(), e); } finally { if (shouldClose) { Utils.consumeFully(entity); } } }
From source file:com.github.lpezet.antiope.dao.DefaultHttpRequestFactory.java
/** Configures the headers in the specified Apache HTTP request. */ private void configureHeaders(HttpRequestBase pHttpRequest, Request<?> pRequest, ExecutionContext pContext, APIConfiguration pConfiguration) { /*/*from w w w . jav a 2 s . co m*/ * Apache HttpClient omits the port number in the Host header (even if * we explicitly specify it) if it's the default port for the protocol * in use. To ensure that we use the same Host header in the request and * in the calculated string to sign (even if Apache HttpClient changed * and started honoring our explicit host with endpoint), we follow this * same behavior here and in the QueryString signer. */ URI endpoint = pRequest.getEndpoint(); String hostHeader = endpoint.getHost(); if (HttpUtils.isUsingNonDefaultPort(endpoint)) { hostHeader += COLON + endpoint.getPort(); } pHttpRequest.addHeader(HOST, hostHeader); // Copy over any other headers already in our request for (Entry<String, String> entry : pRequest.getHeaders().entrySet()) { /* * HttpClient4 fills in the Content-Length header and complains if * it's already present, so we skip it here. We also skip the Host * header to avoid sending it twice, which will interfere with some * signing schemes. */ if (entry.getKey().equalsIgnoreCase(CONTENT_LENGTH) || entry.getKey().equalsIgnoreCase(HOST)) continue; pHttpRequest.addHeader(entry.getKey(), entry.getValue()); } /* Set content type and encoding */ if (pHttpRequest.getHeaders(CONTENT_TYPE) == null || pHttpRequest.getHeaders(CONTENT_TYPE).length == 0) { pHttpRequest.addHeader(CONTENT_TYPE, "application/x-www-form-urlencoded; " + "charset=" + DEFAULT_ENCODING.toLowerCase()); } // Override the user agent string specified in the client params if the // context requires it if (pContext != null && pContext.getContextUserAgent() != null) { pHttpRequest.addHeader(USER_AGENT, createUserAgentString(pConfiguration, pContext.getContextUserAgent())); } }
From source file:de.stklcode.jvault.connector.HTTPVaultConnector.java
/** * Execute prepared HTTP request and return result. * * @param base Prepares Request/*from ww w. j av a2 s .c o m*/ * @param retries number of retries * @return HTTP response * @throws VaultConnectorException on connection error */ private String request(final HttpRequestBase base, final int retries) throws VaultConnectorException { /* Set JSON Header */ base.addHeader("accept", "application/json"); CloseableHttpResponse response = null; try (CloseableHttpClient httpClient = HttpClientBuilder.create() .setSSLSocketFactory(createSSLSocketFactory()).build()) { /* Set custom timeout, if defined */ if (this.timeout != null) base.setConfig(RequestConfig.copy(RequestConfig.DEFAULT).setConnectTimeout(timeout).build()); /* Execute request */ response = httpClient.execute(base); /* Check if response is valid */ if (response == null) throw new InvalidResponseException("Response unavailable"); switch (response.getStatusLine().getStatusCode()) { case 200: return handleResult(response); case 204: return ""; case 403: throw new PermissionDeniedException(); default: if (response.getStatusLine().getStatusCode() >= 500 && response.getStatusLine().getStatusCode() < 600 && retries > 0) { /* Retry on 5xx errors */ return request(base, retries - 1); } else { /* Fail on different error code and/or no retries left */ handleError(response); /* Throw exception withoud details, if response entity is empty. */ throw new InvalidResponseException(Error.RESPONSE_CODE, response.getStatusLine().getStatusCode()); } } } catch (IOException e) { throw new InvalidResponseException(Error.READ_RESPONSE, e); } finally { if (response != null && response.getEntity() != null) try { EntityUtils.consume(response.getEntity()); } catch (IOException ignored) { // Exception ignored. } } }
From source file:org.forgerock.openig.handler.ClientHandler.java
/** * Submits the exchange request to the remote server. Creates and populates the exchange * response from that provided by the remote server. *//*from w ww. j ava 2 s . c o m*/ @Override public void handle(Exchange exchange) throws HandlerException, IOException { LogTimer timer = logger.getTimer().start(); // recover any previous response connection, if present if (exchange.response != null && exchange.response.entity != null) { exchange.response.entity.close(); } HttpRequestBase clientRequest = (exchange.request.entity != null ? new EntityRequest(exchange.request) : new NonEntityRequest(exchange.request)); clientRequest.setURI(exchange.request.uri); // connection headers to suppress CaseInsensitiveSet suppressConnection = new CaseInsensitiveSet(); // parse request connection headers to be suppressed in request suppressConnection.clear(); suppressConnection.addAll(new ConnectionHeader(exchange.request).tokens); // request headers for (String name : exchange.request.headers.keySet()) { if (!SUPPRESS_REQUEST_HEADERS.contains(name) && !suppressConnection.contains(name)) { for (String value : exchange.request.headers.get(name)) { clientRequest.addHeader(name, value); } } } // send request HttpResponse clientResponse = httpClient.execute(clientRequest); exchange.response = new Response(); // response entity HttpEntity clientResponseEntity = clientResponse.getEntity(); if (clientResponseEntity != null) { exchange.response.entity = new BranchingStreamWrapper(clientResponseEntity.getContent(), storage); } // response status line StatusLine statusLine = clientResponse.getStatusLine(); exchange.response.version = statusLine.getProtocolVersion().toString(); exchange.response.status = statusLine.getStatusCode(); exchange.response.reason = statusLine.getReasonPhrase(); // parse response connection headers to be suppressed in response suppressConnection.clear(); suppressConnection.addAll(new ConnectionHeader(exchange.response).tokens); // response headers for (HeaderIterator i = clientResponse.headerIterator(); i.hasNext();) { Header header = i.nextHeader(); String name = header.getName(); if (!SUPPRESS_RESPONSE_HEADERS.contains(name) && !suppressConnection.contains(name)) { exchange.response.headers.add(name, header.getValue()); } } // TODO: decide if need to try-finally to call httpRequest.abort? timer.stop(); }