Java Code Examples for org.apache.http.httpresponse#getLastHeader()

The following examples show how to use org.apache.http.httpresponse#getLastHeader() . 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: DigitalOceanClient.java    From digitalocean-api-java with MIT License 6 votes vote down vote up
/** Easy method for HTTP header values (first/last) */
private String getSimpleHeaderValue(String header, HttpResponse httpResponse, boolean first) {
  if (StringUtils.isBlank(header)) {
    return StringUtils.EMPTY;
  }

  Header h;
  if (first) {
    h = httpResponse.getFirstHeader(header);
  } else {
    h = httpResponse.getLastHeader(header);
  }
  if (h == null) {
    return null;
  }
  return h.getValue();
}
 
Example 2
Source File: AptProxyFacet.java    From nexus-repository-apt with Eclipse Public License 1.0 5 votes vote down vote up
private DateTime getDateHeader(HttpResponse response, String name) {
  Header h = response.getLastHeader(name);
  if (h != null) {
    try {
      return new DateTime(DateUtils.parseDate(h.getValue()).getTime());
    }
    catch (Exception ex) {
      log.warn("Invalid date '{}', will skip", h);
    }
  }
  return null;
}
 
Example 3
Source File: AptProxyFacet.java    From nexus-repository-apt with Eclipse Public License 1.0 5 votes vote down vote up
private String getQuotedStringHeader(HttpResponse response, String name) {
  Header h = response.getLastHeader(name);
  if (h != null) {
    String value = h.getValue();
    if (!Strings.isNullOrEmpty(value)) {
      if (value.startsWith("\"") && value.endsWith("\"")) {
        return value.substring(1, value.length() - 1);
      }
      else {
        return value;
      }
    }
  }
  return null;
}
 
Example 4
Source File: AptProxyFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private DateTime getDateHeader(final HttpResponse response, final String name) {
  Header h = response.getLastHeader(name);
  if (h != null) {
    try {
      return new DateTime(DateUtils.parseDate(h.getValue()).getTime());
    }
    catch (Exception ex) {
      log.warn("Invalid date '{}', will skip. {}", h, log.isDebugEnabled() ? ex : null);
    }
  }
  return null;
}
 
Example 5
Source File: AptProxyFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private String getQuotedStringHeader(final HttpResponse response, final String name) {
  Header h = response.getLastHeader(name);
  if (h != null) {
    String value = h.getValue();
    if (!Strings.isNullOrEmpty(value)) {
      if (value.startsWith("\"") && value.endsWith("\"")) {
        return value.substring(1, value.length() - 1);
      }
      else {
        return value;
      }
    }
  }
  return null;
}
 
Example 6
Source File: ProxyFacetSupport.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Extract Last-Modified date from response if possible, or {@code null}.
 */
@Nullable
private DateTime extractLastModified(final HttpRequestBase request, final HttpResponse response) {
  final Header lastModifiedHeader = response.getLastHeader(HttpHeaders.LAST_MODIFIED);
  if (lastModifiedHeader != null) {
    try {
      return new DateTime(DateUtils.parseDate(lastModifiedHeader.getValue()).getTime());
    }
    catch (Exception ex) {
      log.warn("Could not parse date '{}' received from {}; using system current time as item creation time",
          lastModifiedHeader, request.getURI());
    }
  }
  return null;
}
 
Example 7
Source File: ApiProxyServlet.java    From onboard with Apache License 2.0 5 votes vote down vote up
protected boolean doResponseRedirectOrNotModifiedLogic(HttpServletRequest servletRequest,
        HttpServletResponse servletResponse, HttpResponse proxyResponse, int statusCode) throws ServletException, IOException {
    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    if (statusCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
            && statusCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
        Header locationHeader = proxyResponse.getLastHeader(HttpHeaders.LOCATION);
        if (locationHeader == null) {
            throw new ServletException("Received status code: " + statusCode + " but no " + HttpHeaders.LOCATION
                    + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String locStr = rewriteUrlFromResponse(servletRequest, locationHeader.getValue());

        servletResponse.sendRedirect(locStr);
        return true;
    }
    // 304 needs special handling. See:
    // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
    // We get a 304 whenever passed an 'If-Modified-Since'
    // header and the data on disk has not changed; server
    // responds w/ a 304 saying I'm not going to send the
    // body because the file has not changed.
    if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
        servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0);
        servletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return true;
    }
    return false;
}
 
Example 8
Source File: ApacheHttpClientIT.java    From uavstack with Apache License 2.0 4 votes vote down vote up
/**
 * for http client
 * 
 * @param args
 * @return
 */
public void doEnd(Object[] args) {

    Map<String, Object> params = new HashMap<String, Object>();

    String server = "";

    int rc = -1;

    String responseState = "";

    if (Throwable.class.isAssignableFrom(args[0].getClass())) {

        Throwable e = (Throwable) args[0];

        responseState = e.toString();
    }
    else {
        HttpResponse response = (HttpResponse) args[0];

        Header sheader = response.getLastHeader("Server");

        if (sheader != null) {
            server = sheader.getValue();
        }

        responseState = response.getStatusLine().getStatusCode() + "";

        rc = 1;
    }

    if (logger.isDebugable()) {
        logger.debug("Invoke END:" + rc + "," + server, null);
    }

    params.put(CaptureConstants.INFO_CLIENT_TARGETSERVER, server);
    params.put(CaptureConstants.INFO_CLIENT_RESPONSECODE, rc);
    params.put(CaptureConstants.INFO_CLIENT_TYPE, "apache.http.Client");
    params.put(CaptureConstants.INFO_CLIENT_APPID, this.applicationId);
    params.put(CaptureConstants.INFO_CLIENT_REQUEST_URL, targetURl);
    params.put(CaptureConstants.INFO_CLIENT_RESPONSESTATE, responseState);

    UAVServer.instance().runMonitorCaptureOnServerCapPoint(CaptureConstants.CAPPOINT_APP_CLIENT,
            Monitor.CapturePhase.DOCAP, params);

    if (ivcContextParams != null) {
        ivcContextParams.putAll(params);
    }

    UAVServer.instance().runSupporter("com.creditease.uav.apm.supporters.InvokeChainSupporter", "runCap",
            InvokeChainConstants.CHAIN_APP_CLIENT, InvokeChainConstants.CapturePhase.DOCAP, ivcContextParams,
            ApacheHttpClientAdapter.class, args);
}
 
Example 9
Source File: ProxyFacetSupport.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
protected Content fetch(String url, Context context, @Nullable Content stale) throws IOException {
  HttpClient client = httpClient.getHttpClient();

  checkState(config.remoteUrl.isAbsolute(),
      "Invalid remote URL '%s' for proxy repository %s, please fix your configuration", config.remoteUrl,
      getRepository().getName());
  URI uri;
  try {
    uri = config.remoteUrl.resolve(url);
  }
  catch (IllegalArgumentException e) { // NOSONAR
    log.warn("Unable to resolve url. Reason: {}", e.getMessage());
    throw new BadRequestException("Invalid repository path");
  }
  HttpRequestBase request = buildFetchHttpRequest(uri, context);
  if (stale != null) {
    final DateTime lastModified = stale.getAttributes().get(Content.CONTENT_LAST_MODIFIED, DateTime.class);
    if (lastModified != null) {
      request.addHeader(HttpHeaders.IF_MODIFIED_SINCE, DateUtils.formatDate(lastModified.toDate()));
    }
    final String etag = stale.getAttributes().get(Content.CONTENT_ETAG, String.class);
    if (etag != null) {
      request.addHeader(HttpHeaders.IF_NONE_MATCH, ETagHeaderUtils.quote(etag));
    }
  }
  log.debug("Fetching: {}", request);

  HttpResponse response = execute(context, client, request);
  log.debug("Response: {}", response);

  StatusLine status = response.getStatusLine();
  log.debug("Status: {}", status);

  mayThrowBypassHttpErrorException(response);

  final CacheInfo cacheInfo = getCacheController(context).current();

  if (status.getStatusCode() == HttpStatus.SC_OK) {
    HttpEntity entity = response.getEntity();
    log.debug("Entity: {}", entity);

    final Content result = createContent(context, response);
    result.getAttributes().set(Content.CONTENT_LAST_MODIFIED, extractLastModified(request, response));
    final Header etagHeader = response.getLastHeader(HttpHeaders.ETAG);
    result.getAttributes().set(Content.CONTENT_ETAG, etagHeader == null ? null : ETagHeaderUtils.extract(etagHeader.getValue()));

    result.getAttributes().set(CacheInfo.class, cacheInfo);
    return result;
  }

  try {
    if (status.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
      checkState(stale != null, "Received 304 without conditional GET (bad server?) from %s", uri);
      indicateVerified(context, stale, cacheInfo);
    }
    mayThrowProxyServiceException(response);
  }
  finally {
    HttpClientUtils.closeQuietly(response);
  }

  return null;
}
 
Example 10
Source File: RemoteSystemClient.java    From ghwatch with Apache License 2.0 4 votes vote down vote up
private static String getHeaderValue(HttpResponse httpResponse, String headerName) {
  Header header = httpResponse.getLastHeader(headerName);
  if (header != null)
    return Utils.trimToNull(header.getValue());
  return null;
}