Java Code Examples for org.apache.http.Header#getName()

The following examples show how to use org.apache.http.Header#getName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LoggingHttpRequestExecutor.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected HttpResponse doSendRequest(final HttpRequest request, final HttpClientConnection conn, final HttpContext context) throws IOException, HttpException {
    synchronized(listener) {
        listener.log(TranscriptListener.Type.request, request.getRequestLine().toString());
        for(Header header : request.getAllHeaders()) {
            switch(header.getName()) {
                case HttpHeaders.AUTHORIZATION:
                case HttpHeaders.PROXY_AUTHORIZATION:
                case "X-Auth-Key":
                case "X-Auth-Token":
                    listener.log(TranscriptListener.Type.request, String.format("%s: %s", header.getName(),
                            StringUtils.repeat("*", Integer.min(8, StringUtils.length(header.getValue())))));
                    break;
                default:
                    listener.log(TranscriptListener.Type.request, header.toString());
                    break;
            }
        }
    }
    final HttpResponse response = super.doSendRequest(request, conn, context);
    if(null != response) {
        // response received as part of an expect-continue handshake
        this.log(response);
    }
    return response;
}
 
Example 2
Source File: AccountAttachmentODataConsumer.java    From C4CODATAAPIDEVGUIDE with Apache License 2.0 6 votes vote down vote up
private HttpResponse executeBatchCall(String serviceUrl, final String body)
		throws ClientProtocolException, IOException {
	final HttpPost post = new HttpPost(URI.create(serviceUrl + "/$batch"));
	post.setHeader("Content-Type", "multipart/mixed;boundary=" + boundary);
	post.setHeader(AUTHORIZATION_HEADER, getAuthorizationHeader());
	post.setHeader(CSRF_TOKEN_HEADER, getCsrfToken());

	HttpEntity entity = new StringEntity(body);

	post.setEntity(entity);

	String logText = "REQUEST HEADERS:\n";
	for (Header h : post.getAllHeaders()) {
		logText = logText + h.getName() + " : " + h.getValue() + "\n";
	}
	logger.info(logText);

	HttpResponse response = getHttpClient().execute(post);

	logger.info("$Batch Response statusCode => "
			+ response.getStatusLine().getStatusCode());

	return response;
}
 
Example 3
Source File: ApacheHttpClient.java    From msf4j with Apache License 2.0 6 votes vote down vote up
Response toFeignResponse(HttpResponse httpResponse) throws IOException {
    StatusLine statusLine = httpResponse.getStatusLine();
    int statusCode = statusLine.getStatusCode();

    String reason = statusLine.getReasonPhrase();

    Map<String, Collection<String>> headers = new HashMap<String, Collection<String>>();
    for (Header header : httpResponse.getAllHeaders()) {
        String name = header.getName();
        String value = header.getValue();

        Collection<String> headerValues = headers.get(name);
        if (headerValues == null) {
            headerValues = new ArrayList<String>();
            headers.put(name, headerValues);
        }
        headerValues.add(value);
    }

    return Response.builder()
            .status(statusCode)
            .reason(reason)
            .headers(headers)
            .body(toFeignBody(httpResponse))
            .build();
}
 
Example 4
Source File: DefaultDispatch.java    From knox with Apache License 2.0 6 votes vote down vote up
private String calculateResponseHeaderValue(Header headerToCheck, Map<String, Set<String>> excludedHeaderDirectives) {
  final String headerNameToCheck = headerToCheck.getName();
  if (excludedHeaderDirectives != null && excludedHeaderDirectives.containsKey(headerNameToCheck)) {
    final Set<String> excludedHeaderValues = excludedHeaderDirectives.get(headerNameToCheck);
    if (!excludedHeaderValues.isEmpty()) {
      if (excludedHeaderValues.stream().anyMatch(e -> e.equals(EXCLUDE_ALL))) {
        return ""; // we should exclude all -> there should not be any value added with this header
      } else {
        final String separator = SET_COOKIE.equalsIgnoreCase(headerNameToCheck) ? "; " : " ";
        Set<String> headerValuesToCheck = new HashSet<>(Arrays.asList(headerToCheck.getValue().trim().split("\\s+")));
        headerValuesToCheck = headerValuesToCheck.stream().map(h -> h.replaceAll(separator.trim(), "")).collect(Collectors.toSet());
        headerValuesToCheck.removeAll(excludedHeaderValues);
        return headerValuesToCheck.isEmpty() ? "" : String.join(separator, headerValuesToCheck);
      }
    }
  }

  return headerToCheck.getValue();
}
 
Example 5
Source File: HttpUtil.java    From anyline with Apache License 2.0 5 votes vote down vote up
private static HttpResult parseResult(HttpResult result, CloseableHttpResponse response, String encode) {
	if (null == result) {
		result = new HttpResult();
	} 
	try {
		if(null != response){ 
			Map<String, String> headers = new HashMap<String, String>(); 
			Header[] all = response.getAllHeaders(); 
			for (Header header : all) { 
				String key = header.getName(); 
				String value = header.getValue(); 
				headers.put(key, value); 
				if ("Set-Cookie".equalsIgnoreCase(key)) { 
					HttpCookie c = new HttpCookie(value);
					result.setCookie(c);
				} 
			} 
			int code = response.getStatusLine().getStatusCode();
			result.setHeaders(headers);
			result.setStatus(code);
			if(code ==200){ 
				HttpEntity entity = response.getEntity(); 
				if (null != entity) {
					result.setInputStream(entity.getContent());
					String text = EntityUtils.toString(entity, encode);
					result.setText(text);
				} 
			} 
		} 
	} catch (Exception e) { 
		e.printStackTrace(); 
	} 
	return result;
}
 
Example 6
Source File: ResponseSender.java    From esigate with Apache License 2.0 5 votes vote down vote up
void sendHeaders(HttpResponse httpResponse, IncomingRequest httpRequest, HttpServletResponse response) {
    response.setStatus(httpResponse.getStatusLine().getStatusCode());
    for (Header header : httpResponse.getAllHeaders()) {
        String name = header.getName();
        String value = header.getValue();
        response.addHeader(name, value);
    }

    // Copy new cookies
    Cookie[] newCookies = httpRequest.getNewCookies();

    for (Cookie newCooky : newCookies) {

        // newCooky may be null. In that case just ignore.
        // See https://github.com/esigate/esigate/issues/181
        if (newCooky != null) {
            response.addHeader("Set-Cookie", CookieUtil.encodeCookie(newCooky));
        }
    }
    HttpEntity httpEntity = httpResponse.getEntity();
    if (httpEntity != null) {
        long contentLength = httpEntity.getContentLength();
        if (contentLength > -1 && contentLength < Integer.MAX_VALUE) {
            response.setContentLength((int) contentLength);
        }
        Header contentType = httpEntity.getContentType();
        if (contentType != null) {
            response.setContentType(contentType.getValue());
        }
        Header contentEncoding = httpEntity.getContentEncoding();
        if (contentEncoding != null) {
            response.setHeader(contentEncoding.getName(), contentEncoding.getValue());
        }
    }
}
 
Example 7
Source File: WarcRecord.java    From BUbiNG with Apache License 2.0 5 votes vote down vote up
/**
 * Determines the WARC record type given the <code>WARC-Type</code> header.
 *
 * @param header the header.
 * @return the record type.
 */
public static Type valueOf(final Header header) {
	if (! header.getName().equals(WarcHeader.Name.WARC_TYPE.value)) throw new IllegalArgumentException("Wrong header type " + header.getName());
	final String type = header.getValue();
	if (type.equals(RESPONSE.value))
		return RESPONSE;
	if (type.equals(REQUEST.value))
		return REQUEST;
	if (type.equals(WARCINFO.value))
		return WARCINFO;
	throw new IllegalArgumentException("Unrecognized type " + type);
}
 
Example 8
Source File: HeaderManager.java    From esigate with Apache License 2.0 5 votes vote down vote up
/**
 * Copy header from originalRequest to httpRequest.
 * <p>
 * Referer is rewritten. X-Forwarded-* headers are updated.
 * 
 * @param originalRequest
 *            source request
 * @param httpRequest
 *            destination request
 */
public void copyHeaders(DriverRequest originalRequest, HttpRequest httpRequest) {
    String baseUrl = originalRequest.getBaseUrl().toString();
    String visibleBaseUrl = originalRequest.getVisibleBaseUrl();
    for (Header header : originalRequest.getOriginalRequest().getAllHeaders()) {
        String name = header.getName();
        // Special headers
        if (HttpHeaders.REFERER.equalsIgnoreCase(name) && isForwardedRequestHeader(HttpHeaders.REFERER)) {
            String value = header.getValue();
            value = urlRewriter.rewriteReferer(value, baseUrl, visibleBaseUrl);
            httpRequest.addHeader(name, value);
            // All other headers are copied if allowed
        } else if (isForwardedRequestHeader(name)) {
            httpRequest.addHeader(header);
        }
    }
    // process X-Forwarded-For header
    String remoteAddr = originalRequest.getOriginalRequest().getRemoteAddr();

    if (remoteAddr != null) {
        String forwardedFor = null;
        if (httpRequest.containsHeader("X-Forwarded-For")) {
            forwardedFor = httpRequest.getFirstHeader("X-Forwarded-For").getValue();
        }

        if (forwardedFor == null) {
            forwardedFor = remoteAddr;
        } else {
            forwardedFor = forwardedFor + ", " + remoteAddr;
        }

        httpRequest.setHeader("X-Forwarded-For", forwardedFor);
    }

    // Process X-Forwarded-Proto header
    if (!httpRequest.containsHeader("X-Forwarded-Proto")) {
        httpRequest.addHeader("X-Forwarded-Proto",
                UriUtils.extractScheme(originalRequest.getOriginalRequest().getRequestLine().getUri()));
    }
}
 
Example 9
Source File: BasicHttpClient.java    From zerocode with Apache License 2.0 5 votes vote down vote up
/**
 * Once the client executes the http call, then it receives the http response. This method takes care of handling
 * that. In case you need to handle it differently you can override this method.
 *
 * @param httpResponse  : Received Apache http response from the server
 *
 * @return  : Effective response with handled http session.
 * @throws IOException
 */
public Response handleResponse(CloseableHttpResponse httpResponse) throws IOException {
    Response serverResponse = createCharsetResponse(httpResponse);

    Header[] allHeaders = httpResponse.getAllHeaders();
    Response.ResponseBuilder responseBuilder = Response.fromResponse(serverResponse);
    for (Header thisHeader : allHeaders) {
        String headerKey = thisHeader.getName();
        responseBuilder = responseBuilder.header(headerKey, thisHeader.getValue());

        handleHttpSession(serverResponse, headerKey);
    }

    return responseBuilder.build();
}
 
Example 10
Source File: ApacheHttpClientProviderTest.java    From here-aaa-java-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void test_ApacheHttpClientResponse_additionalHeaders() throws HttpException, IOException {
    String requestBodyJson = "{\"foo\":\"bar\"}";
    url = "http://google.com";

    httpProvider = ApacheHttpClientProvider.builder().build();
    httpRequest = httpProvider.getRequest(httpRequestAuthorizer, "PUT", url, requestBodyJson);

    final String additionalHeaderName = "foohead";
    final String additionalHeaderValue = "barval";
    httpRequest.addHeader(additionalHeaderName, additionalHeaderValue);

    HttpRequestBase httpRequestBase = ApacheHttpClientProviderExposer.getHttpRequestBase(httpRequest);
    Header[] headers = httpRequestBase.getHeaders(additionalHeaderName);
    assertTrue("headers was null", null != headers);
    int expectedLength = 1;
    int length = headers.length;
    assertTrue("headers was expected length " + expectedLength + ", actual length " + length,
    expectedLength == length);
    Header header = headers[0];
    assertTrue("header was null", null != header);
    String name = header.getName();
    String value = header.getValue();
    assertTrue("name was expected " + additionalHeaderName + ", actual " + name,
    additionalHeaderName.equals(name));
    assertTrue("value was expected " + additionalHeaderValue + ", actual " + value,
    additionalHeaderValue.equals(value));

}
 
Example 11
Source File: NiFiHaDispatch.java    From knox with Apache License 2.0 5 votes vote down vote up
/**
 * Overridden to provide a spot to modify the outbound response before its stream is closed.
 */
@Override
protected void writeOutboundResponse(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest, HttpServletResponse outboundResponse, HttpResponse inboundResponse) throws IOException {
  // Copy the client respond header to the server respond.
  outboundResponse.setStatus(inboundResponse.getStatusLine().getStatusCode());
  Header[] headers = inboundResponse.getAllHeaders();
  Set<String> excludeHeaders = getOutboundResponseExcludeHeaders();
  boolean hasExcludeHeaders = false;
  if ((excludeHeaders != null) && !(excludeHeaders.isEmpty())) {
    hasExcludeHeaders = true;
  }
  for ( Header header : headers ) {
    String name = header.getName();
    if (hasExcludeHeaders && excludeHeaders.contains(name.toUpperCase(Locale.ROOT))) {
      continue;
    }
    String value = header.getValue();
    outboundResponse.addHeader(name, value);
  }

  HttpEntity entity = inboundResponse.getEntity();
  if( entity != null ) {
    outboundResponse.setContentType( getInboundResponseContentType( entity ) );
    InputStream stream = entity.getContent();
    try {
      NiFiResponseUtil.modifyOutboundResponse(inboundRequest, outboundResponse, inboundResponse);
      writeResponse( inboundRequest, outboundResponse, stream );
    } finally {
      closeInboundResponse( inboundResponse, stream );
    }
  }
}
 
Example 12
Source File: NiFiDispatch.java    From knox with Apache License 2.0 5 votes vote down vote up
/**
 * Overridden to provide a spot to modify the outbound response before its stream is closed.
 */
@Override
protected void writeOutboundResponse(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest, HttpServletResponse outboundResponse, HttpResponse inboundResponse) throws IOException {
  // Copy the client respond header to the server respond.
  outboundResponse.setStatus(inboundResponse.getStatusLine().getStatusCode());
  Header[] headers = inboundResponse.getAllHeaders();
  Set<String> excludeHeaders = getOutboundResponseExcludeHeaders();
  boolean hasExcludeHeaders = false;
  if ((excludeHeaders != null) && !(excludeHeaders.isEmpty())) {
    hasExcludeHeaders = true;
  }
  for ( Header header : headers ) {
    String name = header.getName();
    if (hasExcludeHeaders && excludeHeaders.contains(name.toUpperCase(Locale.ROOT))) {
      continue;
    }
    String value = header.getValue();
    outboundResponse.addHeader(name, value);
  }

  HttpEntity entity = inboundResponse.getEntity();
  if( entity != null ) {
    outboundResponse.setContentType( getInboundResponseContentType( entity ) );
    InputStream stream = entity.getContent();
    try {
      NiFiResponseUtil.modifyOutboundResponse(inboundRequest, outboundResponse, inboundResponse);
      writeResponse( inboundRequest, outboundResponse, stream );
    } finally {
      closeInboundResponse( inboundResponse, stream );
    }
  }
}
 
Example 13
Source File: HttpClient.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
protected void addHeadersFromResponse(HttpResponse response, Header[] respHeaders) {
    for (Header h : respHeaders) {
        String headerName = h.getName();
        String headerValue = h.getValue();
        response.addResponseHeader(headerName, headerValue);
    }
}
 
Example 14
Source File: ApacheHttpResponse.java    From junit-servers with MIT License 5 votes vote down vote up
@Override
public Collection<HttpHeader> getHeaders() {
	final Header[] headers = response.getAllHeaders();
	if (headers == null || headers.length == 0) {
		return emptyList();
	}

	final Map<String, HttpHeader.Builder> builders = new HashMap<>();

	for (Header h : headers) {
		final String name = h.getName();
		final String value = h.getValue();
		final String key = h.getName().toLowerCase();

		HttpHeader.Builder current = builders.get(key);
		if (current == null) {
			current = HttpHeader.builder(name);
			builders.put(key, current);
		}

		current.addValue(value);
	}

	final List<HttpHeader> results = new ArrayList<>(builders.size());
	for (HttpHeader.Builder header : builders.values()) {
		results.add(header.build());
	}

	return unmodifiableList(results);
}
 
Example 15
Source File: GeoServerIT.java    From geowave with Apache License 2.0 4 votes vote down vote up
private String getContent(final HttpResponse r) throws IOException {
  final InputStream is = r.getEntity().getContent();
  final Header encoding = r.getEntity().getContentEncoding();
  final String encodingName = encoding == null ? "UTF-8" : encoding.getName();
  return IOUtils.toString(is, encodingName);
}
 
Example 16
Source File: HeaderManager.java    From esigate with Apache License 2.0 4 votes vote down vote up
/**
 * Copies end-to-end headers from a response received from the server to the response to be sent to the client.
 * 
 * @param outgoingRequest
 *            the request sent
 * @param incomingRequest
 *            the original request received from the client
 * @param httpClientResponse
 *            the response received from the provider application
 * @return the response to be sent to the client
 */
public CloseableHttpResponse copyHeaders(OutgoingRequest outgoingRequest,
        HttpEntityEnclosingRequest incomingRequest, HttpResponse httpClientResponse) {
    HttpResponse result = new BasicHttpResponse(httpClientResponse.getStatusLine());
    result.setEntity(httpClientResponse.getEntity());
    String originalUri = incomingRequest.getRequestLine().getUri();
    String baseUrl = outgoingRequest.getBaseUrl().toString();
    String visibleBaseUrl = outgoingRequest.getOriginalRequest().getVisibleBaseUrl();
    for (Header header : httpClientResponse.getAllHeaders()) {
        String name = header.getName();
        String value = header.getValue();
        try {
            // Ignore Content-Encoding and Content-Type as these headers are
            // set in HttpEntity
            if (!HttpHeaders.CONTENT_ENCODING.equalsIgnoreCase(name)) {
                if (isForwardedResponseHeader(name)) {
                    // Some headers containing an URI have to be rewritten
                    if (HttpHeaders.LOCATION.equalsIgnoreCase(name)
                            || HttpHeaders.CONTENT_LOCATION.equalsIgnoreCase(name)) {
                        // Header contains only an url
                        value = urlRewriter.rewriteUrl(value, originalUri, baseUrl, visibleBaseUrl, true);
                        value = HttpResponseUtils.removeSessionId(value, httpClientResponse);
                        result.addHeader(name, value);
                    } else if ("Link".equalsIgnoreCase(name)) {
                        // Header has the following format
                        // Link: </feed>; rel="alternate"

                        if (value.startsWith("<") && value.contains(">")) {
                            String urlValue = value.substring(1, value.indexOf(">"));

                            String targetUrlValue =
                                    urlRewriter.rewriteUrl(urlValue, originalUri, baseUrl, visibleBaseUrl, true);
                            targetUrlValue = HttpResponseUtils.removeSessionId(targetUrlValue, httpClientResponse);

                            value = value.replace("<" + urlValue + ">", "<" + targetUrlValue + ">");
                        }

                        result.addHeader(name, value);

                    } else if ("Refresh".equalsIgnoreCase(name)) {
                        // Header has the following format
                        // Refresh: 5; url=http://www.example.com
                        int urlPosition = value.indexOf("url=");
                        if (urlPosition >= 0) {
                            value = urlRewriter.rewriteRefresh(value, originalUri, baseUrl, visibleBaseUrl);
                            value = HttpResponseUtils.removeSessionId(value, httpClientResponse);
                        }
                        result.addHeader(name, value);
                    } else if ("P3p".equalsIgnoreCase(name)) {
                        // Do not translate url yet.
                        // P3P is used with a default fixed url most of the
                        // time.
                        result.addHeader(name, value);
                    } else {
                        result.addHeader(header.getName(), header.getValue());
                    }
                }
            }
        } catch (Exception e1) {
            // It's important not to fail here.
            // An application can always send corrupted headers, and we
            // should not crash
            LOG.error("Error while copying headers", e1);
            result.addHeader("X-Esigate-Error", "Error processing header " + name + ": " + value);
        }
    }
    return BasicCloseableHttpResponse.adapt(result);
}
 
Example 17
Source File: MCRSolrProxyServlet.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
private void handleQuery(String queryHandlerPath, HttpServletRequest request, HttpServletResponse resp)
    throws IOException, TransformerException, SAXException {
    ModifiableSolrParams solrParameter = getSolrQueryParameter(request);
    HttpGet solrHttpMethod = MCRSolrProxyServlet.getSolrHttpMethod(queryHandlerPath, solrParameter,
        Optional.ofNullable(request.getParameter(QUERY_CORE_PARAMETER)).orElse(MCRSolrConstants.MAIN_CORE_TYPE));
    try {
        LOGGER.info("Sending Request: {}", solrHttpMethod.getURI());
        HttpResponse response = httpClient.execute(solrHttpMethod);
        int statusCode = response.getStatusLine().getStatusCode();

        // set status code
        resp.setStatus(statusCode);

        boolean isXML = response.getFirstHeader(HTTP.CONTENT_TYPE).getValue().contains("/xml");
        boolean justCopyInput = !isXML;

        // set all headers
        for (Header header : response.getAllHeaders()) {
            LOGGER.debug("SOLR response header: {} - {}", header.getName(), header.getValue());
            String headerName = header.getName();
            if (NEW_HTTP_RESPONSE_HEADER.containsKey(headerName)) {
                String headerValue = NEW_HTTP_RESPONSE_HEADER.get(headerName);
                if (headerValue != null && headerValue.length() > 0) {
                    resp.setHeader(headerName, headerValue);
                }
            } else {
                resp.setHeader(header.getName(), header.getValue());
            }
        }

        HttpEntity solrResponseEntity = response.getEntity();
        if (solrResponseEntity != null) {
            try (InputStream solrResponseStream = solrResponseEntity.getContent()) {
                if (justCopyInput) {
                    // copy solr response to servlet outputstream
                    OutputStream servletOutput = resp.getOutputStream();
                    IOUtils.copy(solrResponseStream, servletOutput);
                } else {
                    MCRStreamContent solrResponse = new MCRStreamContent(solrResponseStream,
                        solrHttpMethod.getURI().toString(),
                        "response");
                    MCRLayoutService.instance().doLayout(request, resp, solrResponse);
                }
            }
        }
    } catch (IOException ex) {
        solrHttpMethod.abort();
        throw ex;
    }
    solrHttpMethod.releaseConnection();
}
 
Example 18
Source File: HttpComponentsConnector.java    From cyberduck with GNU General Public License v3.0 4 votes vote down vote up
@Override
public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException {
    final HttpUriRequest request = this.toUriHttpRequest(clientRequest);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request);

    try {
        final CloseableHttpResponse response;
        response = client.execute(new HttpHost(request.getURI().getHost(), request.getURI().getPort(), request.getURI().getScheme()), request, new BasicHttpContext(context));
        HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(), this.getClass().getName());

        final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null
                ? Statuses.from(response.getStatusLine().getStatusCode())
                : Statuses.from(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());

        final ClientResponse responseContext = new ClientResponse(status, clientRequest);
        final List<URI> redirectLocations = context.getRedirectLocations();
        if(redirectLocations != null && !redirectLocations.isEmpty()) {
            responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1));
        }

        final Header[] respHeaders = response.getAllHeaders();
        final MultivaluedMap<String, String> headers = responseContext.getHeaders();
        for(final Header header : respHeaders) {
            final String headerName = header.getName();
            List<String> list = headers.get(headerName);
            if(list == null) {
                list = new ArrayList<>();
            }
            list.add(header.getValue());
            headers.put(headerName, list);
        }

        final HttpEntity entity = response.getEntity();

        if(entity != null) {
            if(headers.get(HttpHeaders.CONTENT_LENGTH) == null) {
                headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength()));
            }

            final Header contentEncoding = entity.getContentEncoding();
            if(headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) {
                headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue());
            }
        }
        responseContext.setEntityStream(this.toInputStream(response));
        return responseContext;
    }
    catch(final Exception e) {
        throw new ProcessingException(e);
    }
}
 
Example 19
Source File: HttpComponentsConnector.java    From cyberduck with GNU General Public License v3.0 4 votes vote down vote up
@Override
public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException {
    final HttpUriRequest request = this.toUriHttpRequest(clientRequest);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request);

    try {
        final CloseableHttpResponse response;
        response = client.execute(new HttpHost(request.getURI().getHost(), request.getURI().getPort(), request.getURI().getScheme()), request, new BasicHttpContext(context));
        HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(), this.getClass().getName());

        final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null
            ? Statuses.from(response.getStatusLine().getStatusCode())
            : Statuses.from(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());

        final ClientResponse responseContext = new ClientResponse(status, clientRequest);
        final List<URI> redirectLocations = context.getRedirectLocations();
        if(redirectLocations != null && !redirectLocations.isEmpty()) {
            responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1));
        }

        final Header[] respHeaders = response.getAllHeaders();
        final MultivaluedMap<String, String> headers = responseContext.getHeaders();
        for(final Header header : respHeaders) {
            final String headerName = header.getName();
            List<String> list = headers.get(headerName);
            if(list == null) {
                list = new ArrayList<>();
            }
            list.add(header.getValue());
            headers.put(headerName, list);
        }

        final HttpEntity entity = response.getEntity();

        if(entity != null) {
            if(headers.get(HttpHeaders.CONTENT_LENGTH) == null) {
                headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength()));
            }

            final Header contentEncoding = entity.getContentEncoding();
            if(headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) {
                headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue());
            }
        }
        responseContext.setEntityStream(this.toInputStream(response));
        return responseContext;
    }
    catch(final Exception e) {
        throw new ProcessingException(e);
    }
}
 
Example 20
Source File: SpecialRoutesFilter.java    From spring-microservices-in-action with Apache License 2.0 3 votes vote down vote up
/**
 * Convert an array of the {@code Header} objects to 
 * a {@code MultiValueMap} object for the HTTP header.
 * 
 * <p>This is a opposite operation for 
 * the {@link #convertHeaders(headers)} method.
 * 
 * @param  headers
 *         The array of the {@code Header} objects.
 * 
 * @return  The {@code MultiValueMap} object representing the headers.
 */
private MultiValueMap<String, String> revertHeaders(Header[] headers) {
    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    for (Header header : headers) {
        String name = header.getName();
        if (!map.containsKey(name)) {
            map.put(name, new ArrayList<String>());
        }
        map.get(name).add(header.getValue());
    }
    return map;
}