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

The following examples show how to use org.apache.http.Header#getElements() . 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: NUHttpOptions.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
public Set<String> getAllowedMethods(final HttpResponse response) {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }

    HeaderIterator it = response.headerIterator("Allow");
    Set<String> methods = new HashSet<String>();
    while (it.hasNext()) {
        Header header = it.nextHeader();
        HeaderElement[] elements = header.getElements();
        for (HeaderElement element : elements) {
            methods.add(element.getName());
        }
    }
    return methods;
}
 
Example 2
Source File: BasicResponse.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
private static Charset getEncoding(HttpEntity entity) {
    Header header = entity.getContentEncoding();
    if (header == null) {
        return Charset.forName("UTF-8");
    }
    for (HeaderElement headerElement : header.getElements()) {
        for (NameValuePair pair : headerElement.getParameters()) {
            if (pair != null && pair.getValue() != null) {
                if (Charset.isSupported(pair.getValue())) {
                    return Charset.forName(pair.getValue());
                }
            }
        }
    }
    return Charset.forName("UTF-8");
}
 
Example 3
Source File: AppCookieManager.java    From ambari-metrics with Apache License 2.0 6 votes vote down vote up
static String getHadoopAuthCookieValue(Header[] headers) {
  if (headers == null) {
    return null;
  }
  for (Header header : headers) {
    HeaderElement[] elements = header.getElements();
    for (HeaderElement element : elements) {
      String cookieName = element.getName();
      if (cookieName.equals(HADOOP_AUTH)) {
        if (element.getValue() != null) {
          String trimmedVal = element.getValue().trim();
          if (!trimmedVal.isEmpty()) {
            return trimmedVal;
          }
        }
      }
    }
  }
  return null;
}
 
Example 4
Source File: HttpClientResponse.java    From http-api-invoker with MIT License 6 votes vote down vote up
@Override
public Map<String, String> getCookies() {
    Header[] headers = response.getAllHeaders();
    if (headers == null || headers.length == 0) {
        return Collections.emptyMap();
    }
    Map<String, String> map = new HashMap<String, String>();
    for (Header header : headers) {
        if (SET_COOKIE.equalsIgnoreCase(header.getName())) {
            for (HeaderElement element : header.getElements()) {
                map.put(element.getName(), element.getValue());
            }
        }
    }
    return map;
}
 
Example 5
Source File: OtherUtils.java    From BigApp_Discuz_Android with Apache License 2.0 6 votes vote down vote up
public static Charset getCharsetFromHttpRequest(final HttpRequestBase request) {
    if (request == null) return null;
    String charsetName = null;
    Header header = request.getFirstHeader("Content-Type");
    if (header != null) {
        for (HeaderElement element : header.getElements()) {
            NameValuePair charsetPair = element.getParameterByName("charset");
            if (charsetPair != null) {
                charsetName = charsetPair.getValue();
                break;
            }
        }
    }

    boolean isSupportedCharset = false;
    if (!TextUtils.isEmpty(charsetName)) {
        try {
            isSupportedCharset = Charset.isSupported(charsetName);
        } catch (Throwable e) {
        }
    }

    return isSupportedCharset ? Charset.forName(charsetName) : null;
}
 
Example 6
Source File: OtherUtils.java    From BigApp_Discuz_Android with Apache License 2.0 6 votes vote down vote up
public static String getFileNameFromHttpResponse(final HttpResponse response) {
    if (response == null) return null;
    String result = null;
    Header header = response.getFirstHeader("Content-Disposition");
    if (header != null) {
        for (HeaderElement element : header.getElements()) {
            NameValuePair fileNamePair = element.getParameterByName("filename");
            if (fileNamePair != null) {
                result = fileNamePair.getValue();
                // try to get correct encoding str
                result = CharsetUtils.toCharset(result, HTTP.UTF_8, result.length());
                break;
            }
        }
    }
    return result;
}
 
Example 7
Source File: HttpWorker.java    From IGUANA with GNU Affero General Public License v3.0 6 votes vote down vote up
public static String getContentTypeVal(Header header) {
    System.out.println("[DEBUG] HEADER: " + header);
    for (HeaderElement el : header.getElements()) {
        NameValuePair cTypePair = el.getParameterByName("Content-Type");

        if (cTypePair != null && !cTypePair.getValue().isEmpty()) {
            return cTypePair.getValue();
        }
    }
    int index = header.toString().indexOf("Content-Type");
    if (index >= 0) {
        String ret = header.toString().substring(index + "Content-Type".length() + 1);
        if (ret.contains(";")) {
            return ret.substring(0, ret.indexOf(";")).trim();
        }
        return ret.trim();
    }
    return "application/sparql-results+json";
}
 
Example 8
Source File: OtherUtils.java    From android-open-project-demo with Apache License 2.0 6 votes vote down vote up
public static String getFileNameFromHttpResponse(final HttpResponse response) {
    if (response == null) return null;
    String result = null;
    Header header = response.getFirstHeader("Content-Disposition");
    if (header != null) {
        for (HeaderElement element : header.getElements()) {
            NameValuePair fileNamePair = element.getParameterByName("filename");
            if (fileNamePair != null) {
                result = fileNamePair.getValue();
                // try to get correct encoding str
                result = CharsetUtils.toCharset(result, HTTP.UTF_8, result.length());
                break;
            }
        }
    }
    return result;
}
 
Example 9
Source File: HttpClientUtil.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public void process(final HttpResponse response, final HttpContext context)
    throws HttpException, IOException {
  
  HttpEntity entity = response.getEntity();
  Header ceheader = entity.getContentEncoding();
  if (ceheader != null) {
    HeaderElement[] codecs = ceheader.getElements();
    for (int i = 0; i < codecs.length; i++) {
      if (codecs[i].getName().equalsIgnoreCase("gzip")) {
        response
            .setEntity(new GzipDecompressingEntity(response.getEntity()));
        return;
      }
      if (codecs[i].getName().equalsIgnoreCase("deflate")) {
        response.setEntity(new DeflateDecompressingEntity(response
            .getEntity()));
        return;
      }
    }
  }
}
 
Example 10
Source File: URLEncodedUtils.java    From android-open-project-demo with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the entity's Content-Type header is
 * <code>application/x-www-form-urlencoded</code>.
 */
public static boolean isEncoded(final HttpEntity entity) {
    Header h = entity.getContentType();
    if (h != null) {
        HeaderElement[] elems = h.getElements();
        if (elems.length > 0) {
            String contentType = elems[0].getName();
            return contentType.equalsIgnoreCase(CONTENT_TYPE);
        } else {
            return false;
        }
    } else {
        return false;
    }
}
 
Example 11
Source File: HTTPMethod.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get all Request headers as a map of name to list of values.
 * A value may be null.
 *
 * @return Map, may be empty but not null.
 */
public Multimap<String, String> getRequestHeaders() {
  if (this.lastrequest == null)
    return ImmutableMultimap.of();

  ArrayListMultimap<String, String> multimap = ArrayListMultimap.create();
  for (Header header : this.lastrequest.getAllHeaders()) {
    for (HeaderElement element : header.getElements()) {
      multimap.put(element.getName(), element.getValue());
    }
  }
  return multimap;
}
 
Example 12
Source File: ApacheCloudStackClient.java    From apache-cloudstack-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * This method creates a cookie for every {@link HeaderElement} of the {@link Header} given as parameter.
 * Then, it adds this newly created cookie into the {@link CookieStore} provided as parameter.
 */
protected void createAndAddCookiesOnStoreForHeader(CookieStore cookieStore, Header header) {
    for (HeaderElement element : header.getElements()) {
        BasicClientCookie cookie = createCookieForHeaderElement(element);
        cookieStore.addCookie(cookie);
    }
}
 
Example 13
Source File: URLEncodedUtils.java    From BigApp_Discuz_Android with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the entity's Content-Type header is
 * <code>application/x-www-form-urlencoded</code>.
 */
public static boolean isEncoded(final HttpEntity entity) {
    Header h = entity.getContentType();
    if (h != null) {
        HeaderElement[] elems = h.getElements();
        if (elems.length > 0) {
            String contentType = elems[0].getName();
            return contentType.equalsIgnoreCase(CONTENT_TYPE);
        } else {
            return false;
        }
    } else {
        return false;
    }
}
 
Example 14
Source File: XGoogHashHeader.java    From mvn-golang with Apache License 2.0 5 votes vote down vote up
public XGoogHashHeader(@Nonnull @MustNotContainNull final Header[] headers) {
  String md5value = null;
  String crc32value = null;
  String unknownTypeValue = null;
  String unknownValueValue = null;

  boolean dovalid = true;

  try {
    for (final Header header : headers) {
      for (final HeaderElement e : header.getElements()) {
        final String name = e.getName();
        final String value = Hex.encodeHexString(Base64.decodeBase64(e.getValue()));
        if (name.equalsIgnoreCase("md5")) {
          md5value = value;
        } else if (name.equalsIgnoreCase("crc32c")) {
          crc32value = value;
        } else {
          unknownTypeValue = name;
          unknownValueValue = value;
        }
      }
    }
  } catch (ParseException ex) {
    dovalid = false;
  }
  this.md5 = md5value;
  this.crc32c = crc32value;
  this.unknownType = unknownTypeValue;
  this.unknownValue = unknownValueValue;
  this.valid = dovalid;
}
 
Example 15
Source File: SPARQLProtocolSession.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static RDFFormat getContentTypeSerialisation(HttpResponse response) {
	Header[] headers = response.getHeaders("Content-Type");

	Set<RDFFormat> rdfFormats = RDFParserRegistry.getInstance().getKeys();
	if (rdfFormats.isEmpty()) {
		throw new RepositoryException("No tuple RDF parsers have been registered");
	}

	for (Header header : headers) {
		for (HeaderElement element : header.getElements()) {
			// SHACL Validation report Content-Type gets transformed from:
			// application/shacl-validation-report+n-quads => application/n-quads
			// application/shacl-validation-report+ld+json => application/ld+json
			// text/shacl-validation-report+turtle => text/turtle

			String[] split = element.getName().split("\\+");
			StringBuilder serialisation = new StringBuilder(element.getName().split("/")[0] + "/");
			for (int i = 1; i < split.length; i++) {
				serialisation.append(split[i]);
				if (i + 1 < split.length) {
					serialisation.append("+");
				}
			}

			logger.debug("SHACL validation report is serialised as: " + serialisation.toString());

			Optional<RDFFormat> rdfFormat = RDFFormat.matchMIMEType(serialisation.toString(), rdfFormats);

			if (rdfFormat.isPresent()) {
				return rdfFormat.get();
			}
		}
	}

	throw new RepositoryException("Unsupported content-type for SHACL Validation Report: "
			+ Arrays.toString(response.getHeaders("Content-Type")));

}
 
Example 16
Source File: BasicHttpHandler.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
protected void proxyPost(HttpServerExchange exchange, JsonObject body, CloseableHttpClient client, ClientDnsOverwrite dns) {
    String target = dns.transform(URI.create(exchange.getRequestURL())).toString();
    log.info("Requesting remote: {}", target);
    HttpPost req = RestClientUtils.post(target, GsonUtil.get(), body);

    exchange.getRequestHeaders().forEach(header -> {
        header.forEach(v -> {
            String name = header.getHeaderName().toString();
            if (!StringUtils.startsWithIgnoreCase(name, "content-")) {
                req.addHeader(name, v);
            }
        });
    });

    try (CloseableHttpResponse res = client.execute(req)) {
        exchange.setStatusCode(res.getStatusLine().getStatusCode());
        for (Header h : res.getAllHeaders()) {
            for (HeaderElement el : h.getElements()) {
                exchange.getResponseHeaders().add(HttpString.tryFromString(h.getName()), el.getValue());
            }
        }
        res.getEntity().writeTo(exchange.getOutputStream());
        exchange.endExchange();
    } catch (IOException e) {
        log.warn("Unable to make proxy call: {}", e.getMessage(), e);
        throw new InternalServerError(e);
    }
}
 
Example 17
Source File: RawHttpComponentsClient.java    From rawhttp with Apache License 2.0 5 votes vote down vote up
private RawHttpHeaders readHeaders(CloseableHttpResponse response) {
    Header[] allHeaders = response.getAllHeaders();
    RawHttpHeaders.Builder headers = RawHttpHeaders.newBuilder();
    for (Header header : allHeaders) {
        String meta = header.getElements().length > 0 ?
                ";" + Arrays.stream(header.getElements())
                        .flatMap(it -> Arrays.stream(it.getParameters()).map(v -> v.getName() + "=" + v.getValue()))
                        .collect(joining(";")) :
                "";
        headers.with(header.getName(), header.getValue() + meta);
    }
    return headers.build();
}
 
Example 18
Source File: HTTPSession.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
  HttpEntity entity = response.getEntity();
  if (entity != null) {
    Header ceheader = entity.getContentEncoding();
    if (ceheader != null) {
      HeaderElement[] codecs = ceheader.getElements();
      for (HeaderElement h : codecs) {
        if (h.getName().equalsIgnoreCase("deflate")) {
          response.setEntity(new DeflateDecompressingEntity(response.getEntity()));
          return;
        }
      }
    }
  }
}
 
Example 19
Source File: HTTPSession.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
  HttpEntity entity = response.getEntity();
  if (entity != null) {
    Header ceheader = entity.getContentEncoding();
    if (ceheader != null) {
      HeaderElement[] codecs = ceheader.getElements();
      for (HeaderElement h : codecs) {
        if (h.getName().equalsIgnoreCase("gzip")) {
          response.setEntity(new GzipDecompressingEntity(response.getEntity()));
          return;
        }
      }
    }
  }
}
 
Example 20
Source File: HTTPMethod.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get all Response headers as a map of name to list of values.
 * A value may be null.
 *
 * @return Map, may be empty but not null.
 */
public Multimap<String, String> getResponseHeaders() {
  if (this.lastresponse == null)
    return ImmutableMultimap.of();

  ArrayListMultimap<String, String> multimap = ArrayListMultimap.create();
  for (Header header : this.lastresponse.getAllHeaders()) {
    for (HeaderElement element : header.getElements()) {
      multimap.put(element.getName(), element.getValue());
    }
  }
  return multimap;
}