List of usage examples for org.apache.http.client.methods HttpRequestBase getFirstHeader
public Header getFirstHeader(String str)
From source file:com.aol.webservice_base.util.http.HttpHelper.java
/** * Http client call./*w w w .j a v a 2 s . co m*/ * * callers to this are responsible for ensuring connection is closed properly - httpHelper.releaseResponse() * * @param requestMethod the request method * @param url the url * @param headers the headers * @param content the content * @return the http response * @throws HttpException the http exception */ protected HttpResponse httpClientCall(String requestMethod, String url, Map<String, String> headers, Object content) throws HttpException { HttpResponse response = null; if (!inited) { throw new Error("HttpHelper used when not initialized (call init) for " + url); } final String METHOD = "HttpHelper.httpClientCall()"; HttpRequestBase httpRequest = null; boolean success = false; int iter = 0; int status; String statusMsg; do { try { long begin = System.currentTimeMillis(); new URL(url); httpRequest = getHttpRequest(requestMethod, url, content); if (headers != null && headers.size() > 0) { for (Map.Entry<String, String> headerSet : headers.entrySet()) { httpRequest.addHeader(headerSet.getKey(), headerSet.getValue()); } } Header[] requestHeaders = httpRequest.getAllHeaders(); for (int i = 0; i < requestHeaders.length; i++) { String name = requestHeaders[i].getName(); String value = requestHeaders[i].getValue(); if (logger.isDebugEnabled()) { logger.debug("Request header " + name + " = [" + value + "]"); } } // make the request //httpRequest.setFollowRedirects(false); response = httpClient.execute(httpRequest); status = response.getStatusLine().getStatusCode(); statusMsg = response.getStatusLine().getReasonPhrase(); if (logger.isDebugEnabled()) { logger.debug(METHOD + " status=" + status + " status desc: [" + statusMsg + "] url=[" + url + "] took=" + (System.currentTimeMillis() - begin) + " ms"); } if (status == 302 || status == 301) { Header loc = httpRequest.getFirstHeader("Location"); if (loc != null) { String origUrl = url; url = loc.getValue(); if (!url.startsWith("http")) { url = addHost(origUrl, url); } continue; } } if (status != 200 /* && status != 304 */) { throw new HttpException(status, statusMsg); } if (logger.isDebugEnabled()) { Header[] responseHeaders = response.getAllHeaders(); for (int i = 0; i < responseHeaders.length; i++) { String name = responseHeaders[i].getName(); String value = responseHeaders[i].getValue(); logger.debug("Response header " + name + " = [" + value + "]"); } } success = true; return response; } catch (MalformedURLException e) { String msg = "target URL = [" + url + "] is invalid."; logger.error(msg); throw new HttpException(HttpServletResponse.SC_NOT_FOUND, msg); } catch (HttpException e) { logger.error("HttpException " + METHOD + " url=" + url + " exception=" + e.getMessage()); throw e; } catch (java.net.SocketTimeoutException e) { logger.error("SocketTimeoutException " + METHOD + " url=" + url + " exception=" + e.getMessage()); throw new HttpException(HttpServletResponse.SC_GATEWAY_TIMEOUT, "Connection or Read timeout exception: " + e); } catch (Throwable t) { logger.error("HttpException " + METHOD + " url=" + url + " exception=" + t.getMessage()); throw new HttpException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, t); } finally { // release the connection whenever we are not successful if ((!success) && (response != null)) { try { releaseResponse(response); response = null; } catch (IOException e) { logger.error("HttpHelper - problem releasing connection", e); } } } } while (!success && (++iter <= this.followRedirectMax)); throw new HttpException(status, statusMsg); }
From source file:com.baidubce.http.BceHttpClient.java
/** * Creates HttpClient method object based on the specified request and * populates any parameters, headers, etc. from the internal request. * * @param request The request to convert to an HttpClient method object. * @return The converted HttpClient method object with any parameters, headers, etc. from the original request set. *///from www. j ava 2s . c o m protected HttpRequestBase createHttpRequest(InternalRequest request) { String uri = request.getUri().toASCIIString(); String encodedParams = HttpUtils.getCanonicalQueryString(request.getParameters(), false); if (encodedParams.length() > 0) { uri += "?" + encodedParams; } HttpRequestBase httpRequest; long contentLength = -1; String contentLengthString = request.getHeaders().get(Headers.CONTENT_LENGTH); if (contentLengthString != null) { contentLength = Long.parseLong(contentLengthString); } if (request.getHttpMethod() == HttpMethodName.GET) { httpRequest = new HttpGet(uri); } else if (request.getHttpMethod() == HttpMethodName.PUT) { HttpPut putMethod = new HttpPut(uri); httpRequest = putMethod; if (request.getContent() != null) { putMethod.setEntity(new InputStreamEntity(request.getContent(), contentLength)); } } else if (request.getHttpMethod() == HttpMethodName.POST) { HttpPost postMethod = new HttpPost(uri); httpRequest = postMethod; if (request.getContent() != null) { postMethod.setEntity(new InputStreamEntity(request.getContent(), contentLength)); } } else if (request.getHttpMethod() == HttpMethodName.DELETE) { httpRequest = new HttpDelete(uri); } else if (request.getHttpMethod() == HttpMethodName.HEAD) { httpRequest = new HttpHead(uri); } else { throw new BceClientException("Unknown HTTP method name: " + request.getHttpMethod()); } httpRequest.addHeader(Headers.HOST, HttpUtils.generateHostHeader(request.getUri())); // 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(Headers.CONTENT_LENGTH) || entry.getKey().equalsIgnoreCase(Headers.HOST)) { continue; } httpRequest.addHeader(entry.getKey(), entry.getValue()); } checkNotNull(httpRequest.getFirstHeader(Headers.CONTENT_TYPE), Headers.CONTENT_TYPE + " not set"); return httpRequest; }
From source file:org.dasein.cloud.azure.AzureStorageMethod.java
protected HttpRequestBase getMethod(@Nonnull String httpMethod, @Nonnull String endpoint, @Nonnull Map<String, String> queryParams, @Nullable Map<String, String> headers, boolean authorization) throws CloudException, InternalException { HttpRequestBase method;//w w w. ja v a2 s . c o m if (httpMethod.equals("GET")) { method = new HttpGet(endpoint); } else if (httpMethod.equals("POST")) { method = new HttpPost(endpoint); } else if (httpMethod.equals("PUT")) { method = new HttpPut(endpoint); } else if (httpMethod.equals("DELETE")) { method = new HttpDelete(endpoint); } else if (httpMethod.equals("HEAD")) { method = new HttpHead(endpoint); } else if (httpMethod.equals("OPTIONS")) { method = new HttpOptions(endpoint); } else if (httpMethod.equals("HEAD")) { method = new HttpTrace(endpoint); } else { method = new HttpGet(endpoint); } if (!authorization) { return method; } if (headers == null) { headers = new TreeMap<String, String>(); } String RFC1123_PATTERN = "EEE, dd MMM yyyy HH:mm:ss z"; DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN); rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT")); headers.put("Date", rfc1123Format.format(new Date())); headers.put(Header_Prefix_MS + "version", VERSION); for (String key : headers.keySet()) { method.addHeader(key, headers.get(key)); } if (method.getFirstHeader("content-type") == null && !httpMethod.equals("GET")) { method.addHeader("content-type", "application/xml;charset=utf-8"); } method.addHeader("Authorization", "SharedKeyLite " + getStorageAccount() + ":" + calculatedSharedKeyLiteSignature(method, queryParams)); return method; }
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 w w w . j ava 2s . c om*/ // 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:org.artifactory.repo.HttpRepo.java
private String getFilename(HttpRequestBase method, String originalPath) { // Skip filename parsing if we are not dealing with latest maven non-unique snapshot request if (!isRequestForLatestMavenSnapshot(originalPath)) { return null; }/* ww w. j a va 2 s . co m*/ // Try our custom X-Artifactory-Filename header Header filenameHeader = method.getFirstHeader(ArtifactoryRequest.FILE_NAME); if (filenameHeader != null) { String filenameString = filenameHeader.getValue(); try { return URLDecoder.decode(filenameString, "UTF-8"); } catch (UnsupportedEncodingException e) { log.warn("Unable to decode '{}' header '{}', returning un-encoded value.", ArtifactoryRequest.FILE_NAME, filenameString); return filenameString; } } // Didn't find any filename, return null return null; }
From source file:org.openrepose.nodeservice.httpcomponent.RequestProxyServiceImpl.java
private void setHeaders(HttpRequestBase base, Map<String, String> headers) { final Set<Map.Entry<String, String>> entries = headers.entrySet(); for (Map.Entry<String, String> entry : entries) { base.addHeader(entry.getKey(), entry.getValue()); }//from w w w. ja v a2 s . c o m //Tack on the tracing ID for requests via the dist datastore String traceGUID = MDC.get(TracingKey.TRACING_KEY); if (!StringUtils.isEmpty(traceGUID)) { Header viaHeader = base.getFirstHeader(CommonHttpHeader.VIA.toString()); base.addHeader(CommonHttpHeader.TRACE_GUID.toString(), TracingHeaderHelper .createTracingHeader(traceGUID, viaHeader != null ? viaHeader.getValue() : null)); } }