List of usage examples for org.apache.http.client.methods HttpRequestBase getHeaders
public Header[] getHeaders(String str)
From source file:eionet.webq.xforms.XFormsHTTPRequestAuthHandlerImplTest.java
@Test public void noAuthIfDifferentHostAsInstance() { String resourceUrl = "http://resource.xml"; HttpRequestBase httpRequest = new HttpGet(resourceUrl); Map<Object, Object> context = createBfContextMap(); context.put("instance", REQUEST_PARAM_KNOWN_HOST_URL + "/instance.xml"); UserFile userFile = createUserFileWithAuth(); when(userFileService.getById(anyInt())).thenReturn(userFile); when(knownHostsService.getKnownHost(anyString())).thenReturn(null); requestAuthHandler.addAuthToHttpRequest(httpRequest, context); assertThat(httpRequest.getURI().toString(), equalTo(resourceUrl)); assertThat(httpRequest.getHeaders("Authorization").length, equalTo(0)); }
From source file:se.kodapan.io.http.HttpAccessor.java
public Response sendRequest(HttpRequestBase method, boolean followRedirects) throws IOException { // lazy opening if (!open) {//from w w w . j av a 2 s .c om open(); } // Mimics a Firefox on OS X. if (method.getHeaders("User-Agent").length == 0) { method.addHeader("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; sv-SE; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2"); } if (method.getHeaders("Accept").length == 0) { method.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); } if (method.getHeaders("Accept-Language").length == 0) { method.addHeader("Accept-Language", "sv-se,sv;q=0.8,en-us;q=0.5,en;q=0.3"); } if (method.getHeaders("Accept-Charset").length == 0) { method.addHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); } Response response = new Response(); URI url = method.getURI(); response.finalURL = url; if (log.isDebugEnabled()) { log.debug("Requesting " + url); } String tmp = url.toString().toLowerCase(); if (!(tmp.startsWith("http://") || tmp.startsWith("https://"))) { log.error("Unsupported protocol in url " + url); return response; } if (followRedirects) { try { response.success = downloadFollowRedirects(new Request(method), response); } catch (SAXException e) { log.error("Attempting to follow redirection chain", e); return response; } } else { response.success = download(new Request(method), response); } return response; }
From source file:eionet.webq.xforms.XFormsHTTPRequestAuthHandlerImplTest.java
@Test public void addBasicAuthIfSameHostAsInstance() { HttpRequestBase httpRequest = new HttpGet(BASIC_AUTH_KNOWN_HOST_URL + "/resource.xml"); Map<Object, Object> context = createBfContextMap(); context.put("instance", BASIC_AUTH_KNOWN_HOST_URL + "/instance.xml"); UserFile userFile = createUserFileWithAuth(); when(userFileService.getById(anyInt())).thenReturn(userFile); when(knownHostsService.getKnownHost(anyString())).thenReturn(createBasicAuthKnownHost()); requestAuthHandler.addAuthToHttpRequest(httpRequest, context); assertThat(httpRequest.getURI().toString(), equalTo(BASIC_AUTH_KNOWN_HOST_URL + "/resource.xml")); assertThat(httpRequest.getHeaders("Authorization")[0].getValue().trim(), equalTo(userFile.getAuthorization())); }
From source file:com.ksc.http.apache.request.impl.ApacheHttpRequestFactory.java
/** * Configures the headers in the specified Apache HTTP request. *//* w w w .j a v a2 s . c o m*/ private void addHeadersToRequest(HttpRequestBase httpRequest, Request<?> request) { httpRequest.addHeader(HttpHeaders.HOST, getHostHeaderValue(request.getEndpoint())); // 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 (!(ignoreHeaders.contains(entry.getKey()))) { httpRequest.addHeader(entry.getKey(), entry.getValue()); } } /* Set content type and encoding */ if (httpRequest.getHeaders(HttpHeaders.CONTENT_TYPE) == null || httpRequest.getHeaders(HttpHeaders.CONTENT_TYPE).length == 0) { httpRequest.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded; " + "charset=" + DEFAULT_ENCODING.toLowerCase()); } }
From source file:com.mashape.unirest.android.http.HttpClientHelper.java
private static HttpRequestBase prepareRequest(HttpRequest request, boolean async) { Object defaultHeaders = Options.getOption(Option.DEFAULT_HEADERS); if (defaultHeaders != null) { @SuppressWarnings("unchecked") Set<Entry<String, String>> entrySet = ((Map<String, String>) defaultHeaders).entrySet(); for (Entry<String, String> entry : entrySet) { request.header(entry.getKey(), entry.getValue()); }/*from ww w .j a va 2s .c o m*/ } if (!request.getHeaders().containsKey(USER_AGENT_HEADER)) { request.header(USER_AGENT_HEADER, USER_AGENT); } if (!request.getHeaders().containsKey(ACCEPT_ENCODING_HEADER)) { request.header(ACCEPT_ENCODING_HEADER, "gzip"); } HttpRequestBase reqObj = null; String urlToRequest = null; try { URL url = new URL(request.getUrl()); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), URLDecoder.decode(url.getPath(), "UTF-8"), "", url.getRef()); urlToRequest = uri.toURL().toString(); if (url.getQuery() != null && !url.getQuery().trim().equals("")) { if (!urlToRequest.substring(urlToRequest.length() - 1).equals("?")) { urlToRequest += "?"; } urlToRequest += url.getQuery(); } else if (urlToRequest.substring(urlToRequest.length() - 1).equals("?")) { urlToRequest = urlToRequest.substring(0, urlToRequest.length() - 1); } } catch (Exception e) { throw new RuntimeException(e); } switch (request.getHttpMethod()) { case GET: reqObj = new HttpGet(urlToRequest); break; case POST: reqObj = new HttpPost(urlToRequest); break; case PUT: reqObj = new HttpPut(urlToRequest); break; case DELETE: //reqObj = new HttpDeleteWithBody(urlToRequest); break; case PATCH: //reqObj = new HttpPatchWithBody(urlToRequest); break; case OPTIONS: reqObj = new HttpOptions(urlToRequest); break; case HEAD: reqObj = new HttpHead(urlToRequest); break; } Set<Entry<String, List<String>>> entrySet = request.getHeaders().entrySet(); for (Entry<String, List<String>> entry : entrySet) { List<String> values = entry.getValue(); if (values != null) { for (String value : values) { reqObj.addHeader(entry.getKey(), value); } } } // Set body if (!(request.getHttpMethod() == HttpMethod.GET || request.getHttpMethod() == HttpMethod.HEAD)) { if (request.getBody() != null) { HttpEntity entity = request.getBody().getEntity(); if (async) { if (reqObj.getHeaders(CONTENT_TYPE) == null || reqObj.getHeaders(CONTENT_TYPE).length == 0) { reqObj.setHeader(entity.getContentType()); } try { ByteArrayOutputStream output = new ByteArrayOutputStream(); entity.writeTo(output); NByteArrayEntity en = new NByteArrayEntity(output.toByteArray()); ((HttpEntityEnclosingRequestBase) reqObj).setEntity(en); } catch (IOException e) { throw new RuntimeException(e); } } else { ((HttpEntityEnclosingRequestBase) reqObj).setEntity(entity); } } } return reqObj; }
From source file:com.cloudbees.jenkins.plugins.bitbucket.server.client.BitbucketServerAPIClient.java
private String doRequest(HttpRequestBase request) throws IOException { if (authenticator != null) { authenticator.configureRequest(request); }/*w ww . ja v a2 s. c o m*/ try (CloseableHttpClient client = getHttpClient(request); CloseableHttpResponse response = client.execute(request, context)) { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT) { EntityUtils.consume(response.getEntity()); // 204, no content return ""; } String content; long len = -1L; Header[] headers = request.getHeaders("Content-Length"); if (headers != null && headers.length > 0) { int i = headers.length - 1; len = -1L; while (i >= 0) { Header header = headers[i]; try { len = Long.parseLong(header.getValue()); break; } catch (NumberFormatException var5) { --i; } } } if (len == 0) { content = ""; } else { ByteArrayOutputStream buf; if (len > 0 && len <= Integer.MAX_VALUE / 2) { buf = new ByteArrayOutputStream((int) len); } else { buf = new ByteArrayOutputStream(); } try (InputStream is = response.getEntity().getContent()) { IOUtils.copy(is, buf); } content = new String(buf.toByteArray(), StandardCharsets.UTF_8); } EntityUtils.consume(response.getEntity()); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK && response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) { throw new BitbucketRequestException(response.getStatusLine().getStatusCode(), "HTTP request error. Status: " + response.getStatusLine().getStatusCode() + ": " + response.getStatusLine().getReasonPhrase() + ".\n" + response); } return content; } finally { request.releaseConnection(); } }
From source file:org.georchestra.security.Proxy.java
private void handleRequest(HttpServletRequest request, HttpServletResponse finalResponse, RequestType requestType, String sURL, boolean localProxy) { HttpClientBuilder htb = HttpClients.custom().disableRedirectHandling(); RequestConfig config = RequestConfig.custom().setSocketTimeout(this.httpClientTimeout).build(); htb.setDefaultRequestConfig(config); ////from www . ja v a 2 s .c o m // Handle http proxy for external request. // Proxy must be configured by system variables (e.g.: -Dhttp.proxyHost=proxy -Dhttp.proxyPort=3128) htb.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())); HttpClient httpclient = htb.build(); HttpResponse proxiedResponse = null; int statusCode = 500; try { URL url = null; try { url = new URL(sURL); } catch (MalformedURLException e) { // not an url finalResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); return; } // HTTP protocol is required if (!"http".equalsIgnoreCase(url.getProtocol()) && !"https".equalsIgnoreCase(url.getProtocol())) { finalResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "HTTP protocol expected. \"" + url.getProtocol() + "\" used."); return; } // check if proxy must filter on final host if (!strategyForFilteringRequests.allowRequest(url)) { finalResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "Host \"" + url.getHost() + "\" is not allowed to be requested"); return; } logger.debug("Final request -- " + sURL); HttpRequestBase proxyingRequest = makeRequest(request, requestType, sURL); headerManagement.configureRequestHeaders(request, proxyingRequest); try { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Header[] originalHeaders = proxyingRequest.getHeaders("sec-org"); String org = ""; for (Header originalHeader : originalHeaders) { org = originalHeader.getValue(); } // no OGC SERVICE log if request going through /proxy/?url= if (!request.getRequestURI().startsWith("/sec/proxy/")) { String[] roles = new String[] { "" }; try { Header[] rolesHeaders = proxyingRequest.getHeaders("sec-roles"); if (rolesHeaders.length > 0) { roles = rolesHeaders[0].getValue().split(";"); } } catch (Exception e) { logger.error("Unable to compute roles"); } statsLogger.info(OGCServiceMessageFormatter.format(authentication.getName(), sURL, org, roles)); } } catch (Exception e) { logger.error("Unable to log the request into the statistics logger", e); } if (localProxy) { // // Hack for geoserver // Should not be here. We must use a ProxyTarget class and // define // if Host header should be forwarded or not. // request.getHeader("Host"); proxyingRequest.setHeader("Host", request.getHeader("Host")); if (logger.isDebugEnabled()) { logger.debug("Host header set to: " + proxyingRequest.getFirstHeader("Host").getValue() + " for proxy request."); } } proxiedResponse = executeHttpRequest(httpclient, proxyingRequest); StatusLine statusLine = proxiedResponse.getStatusLine(); statusCode = statusLine.getStatusCode(); String reasonPhrase = statusLine.getReasonPhrase(); if (reasonPhrase != null && statusCode > 399) { if (logger.isWarnEnabled()) { logger.warn("Error occurred. statuscode: " + statusCode + ", reason: " + reasonPhrase); } if (statusCode == 401) { // // Handle case of basic authentication. // Header authHeader = proxiedResponse.getFirstHeader("WWW-Authenticate"); finalResponse.setHeader("WWW-Authenticate", (authHeader == null) ? "Basic realm=\"Authentication required\"" : authHeader.getValue()); } // 403 and 404 are handled by specific JSP files provided by the // security-proxy webapp if ((statusCode == 404) || (statusCode == 403)) { finalResponse.sendError(statusCode); return; } } headerManagement.copyResponseHeaders(request, request.getRequestURI(), proxiedResponse, finalResponse, this.targets); if (statusCode == 302 || statusCode == 301) { adjustLocation(request, proxiedResponse, finalResponse); } // get content type String contentType = null; if (proxiedResponse.getEntity() != null && proxiedResponse.getEntity().getContentType() != null) { contentType = proxiedResponse.getEntity().getContentType().getValue(); logger.debug("content-type detected: " + contentType); } // content type has to be valid if (isCharsetRequiredForContentType(contentType)) { doHandleRequestCharsetRequired(request, finalResponse, requestType, proxiedResponse, contentType); } else { logger.debug("charset not required for contentType: " + contentType); doHandleRequest(request, finalResponse, requestType, proxiedResponse); } } catch (IOException e) { // connection problem with the host logger.error("Exception occured when trying to connect to the remote host: ", e); try { finalResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } catch (IOException e2) { // error occured while trying to return the // "service unavailable status" finalResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } finally { httpclient.getConnectionManager().shutdown(); } }
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 w w . j a va 2s. 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.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 www . ja va 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())); } }