下面列出了org.apache.http.HeaderElement#getName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Bean
public ConnectionKeepAliveStrategy connectionKeepAliveStrategy() {
return (httpResponse, httpContext) -> {
HeaderIterator headerIterator = httpResponse.headerIterator(HTTP.CONN_KEEP_ALIVE);
HeaderElementIterator elementIterator = new BasicHeaderElementIterator(headerIterator);
while (elementIterator.hasNext()) {
HeaderElement element = elementIterator.nextElement();
String param = element.getName();
String value = element.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
return Long.parseLong(value) * 1000; // convert to ms
}
}
return DEFAULT_KEEP_ALIVE_TIME;
};
}
@Bean
public ConnectionKeepAliveStrategy connectionKeepAliveStrategy() {
return new ConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
HeaderElementIterator it = new BasicHeaderElementIterator(
response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
return Long.parseLong(value) * 1000;
}
}
return httpClientProperties.getDefaultKeepAliveTimeMillis();
}
};
}
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;
}
@Bean
public ConnectionKeepAliveStrategy connectionKeepAliveStrategy() {
return new ConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext httpContext) {
HeaderElementIterator it = new BasicHeaderElementIterator
(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
return Long.parseLong(value) * 1000;
}
}
return p.getDefaultKeepAliveTimeMillis();
}
};
}
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
long timeout = Long.parseLong(value) * 1000;
if (timeout > 20 * 1000) {
return 20 * 1000;
} else {
return timeout;
}
}
}
return 5 * 1000;
}
/**
* Gets the MIME type specified in the response headers of the supplied method, if any. For example, if the response
* headers contain <tt>Content-Type: application/xml;charset=UTF-8</tt>, this method will return
* <tt>application/xml</tt> as the MIME type.
*
* @param method The method to get the reponse MIME type from.
* @return The response MIME type, or <tt>null</tt> if not available.
*/
protected String getResponseMIMEType(HttpResponse method) throws IOException {
Header[] headers = method.getHeaders("Content-Type");
for (Header header : headers) {
HeaderElement[] headerElements = header.getElements();
for (HeaderElement headerEl : headerElements) {
String mimeType = headerEl.getName();
if (mimeType != null) {
logger.debug("response MIME type is {}", mimeType);
return mimeType;
}
}
}
return null;
}
private ConnectionKeepAliveStrategy createKeepAliveStrategy() {
return new ConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(HttpResponse httpResponse, HttpContext httpContext) {
// in case of errors keep-alive not always works. close connection just in case
if (httpResponse.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) {
return -1;
}
HeaderElementIterator it = new BasicHeaderElementIterator(
httpResponse.headerIterator(HTTP.CONN_DIRECTIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
//String value = he.getValue();
if (param != null && param.equalsIgnoreCase(HTTP.CONN_KEEP_ALIVE)) {
return properties.getKeepAliveTimeout();
}
}
return -1;
}
};
}
@Override
public long getKeepAliveDuration(final HttpResponse response, final HttpContext context) {
// Honor 'keep-alive' header
final HeaderElementIterator it = new BasicHeaderElementIterator(
response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
final HeaderElement he = it.nextElement();
final String param = he.getName();
final String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
try {
return Long.parseLong(value) * 1000;
} catch (NumberFormatException ignore) {
// Do nothing
}
}
}
// otherwise keep alive for 30 seconds
return 30 * 1000;
}
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
try {
return Long.parseLong(value) * 1000;
} catch (NumberFormatException ignore) {
}
}
}
return DEFAULT_KEEP_ALIVE_DURATION;
}
@Override
public long getKeepAliveDuration(HttpResponse httpResponse, HttpContext httpContext) {
HeaderElementIterator headerElementIterator = new BasicHeaderElementIterator(
httpResponse.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (headerElementIterator.hasNext()) {
HeaderElement headerElement = headerElementIterator.nextElement();
String name = headerElement.getName();
String value = headerElement.getValue();
if (value != null && name.equalsIgnoreCase("timeout")) {
return Long.parseLong(value) * 1000;
}
}
// Set own keep alive duration if server does not have it
return appConfiguration.getRptConnectionPoolCustomKeepAliveTimeout() * 1000;
}
/**
* @return The connection keep alive strategy.
*/
private ConnectionKeepAliveStrategy getKeepAliveStrategy() {
return (response, context) -> {
// Honor 'keep-alive' header
HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && "timeout".equalsIgnoreCase(param)) {
try {
return Long.parseLong(value) * 1000;
} catch (NumberFormatException ignore) {
// let's move on the next header value
break;
}
}
}
// otherwise use the default value
return defaultKeepAlive * 1000;
};
}
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
HeaderElementIterator it = new BasicHeaderElementIterator(
response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
try {
return Long.parseLong(value) * 1000;
} catch (NumberFormatException ignore) {
}
}
}
return keepAliveTimeOut * 1000;
}
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
HeaderElementIterator it = new BasicHeaderElementIterator(
response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
try {
return Long.parseLong(value) * 1000;
} catch (NumberFormatException ignore) {
}
}
}
return keepAliveTimeOut * 1000;
}
public static ConnectionKeepAliveStrategy create(long keepTimeMill) {
if (keepTimeMill < 0)
throw new IllegalArgumentException("apache_httpclient连接持久时间不能小于0");
return new ConnectionKeepAliveStrategy() {
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
// Honor 'keep-alive' header
HeaderElementIterator it = new BasicHeaderElementIterator(
response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
try {
return Long.parseLong(value) * 1000;
} catch (NumberFormatException ignore) {
}
}
}
return keepTimeMill;
}
};
}
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;
}
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && param.equalsIgnoreCase(KEEP_ALIVE_TIMEOUT_PARAM_NAME)) {
return Long.parseLong(value) * 1000;
}
}
return DEFAULT_KEEP_ALIVE_TIMEOUT_MS;
}
/**
* This method will create a {@link BasicClientCookie} with the given {@link HeaderElement}.
* It sill set the cookie's name and value according to the {@link HeaderElement#getName()} and {@link HeaderElement#getValue()} methods.
* Moreover, it will transport every {@link HeaderElement} parameter to the cookie using the {@link BasicClientCookie#setAttribute(String, String)}.
* Additionally, it configures the cookie path ({@link BasicClientCookie#setPath(String)}) to value '/client/api' and the cookie domain using {@link #configureDomainForCookie(BasicClientCookie)} method.
*/
protected BasicClientCookie createCookieForHeaderElement(HeaderElement element) {
BasicClientCookie cookie = new BasicClientCookie(element.getName(), element.getValue());
for (NameValuePair parameter : element.getParameters()) {
cookie.setAttribute(parameter.getName(), parameter.getValue());
}
cookie.setPath("/client/api");
configureDomainForCookie(cookie);
return cookie;
}
@Test
// @Ignore
// 5.1
public final void whenCustomizingKeepAliveStrategy_thenNoExceptions() throws ClientProtocolException, IOException {
final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(final HttpResponse myResponse, final HttpContext myContext) {
final HeaderElementIterator it = new BasicHeaderElementIterator(myResponse.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
final HeaderElement he = it.nextElement();
final String param = he.getName();
final String value = he.getValue();
if ((value != null) && param.equalsIgnoreCase("timeout")) {
return Long.parseLong(value) * 1000;
}
}
final HttpHost target = (HttpHost) myContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
if ("localhost".equalsIgnoreCase(target.getHostName())) {
return 10 * 1000;
} else {
return 5 * 1000;
}
}
};
client = HttpClients.custom().setKeepAliveStrategy(myStrategy).setConnectionManager(poolingConnManager).build();
client.execute(get1);
client.execute(get2);
}
private static ContentType create(final HeaderElement helem) {
String mimeType = helem.getName();
String charset = null;
NameValuePair param = helem.getParameterByName("charset");
if (param != null) {
charset = param.getValue();
}
return create(mimeType, charset);
}
@PostConstruct
public void init() {
poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
poolingHttpClientConnectionManager.setMaxTotal(maxTotalConnections);
poolingHttpClientConnectionManager
.setDefaultMaxPerRoute(this.maxConnectionsPerRoute);
ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
public long getKeepAliveDuration(HttpResponse response,
HttpContext context) {
HeaderElementIterator it = new BasicHeaderElementIterator(
response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
try {
return Long.parseLong(value) * 1000;
} catch (NumberFormatException ignore) {
}
}
}
return keepAliveDurationMilliseconds;
}
};
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
if (isProxyNeeded) {
requestConfigBuilder.setProxy(new HttpHost(proxyHost, proxyPort));
}
RequestConfig requestConfig = requestConfigBuilder
.setConnectionRequestTimeout(this.connReqTimeoutMilliseconds)
.setConnectTimeout(connTimeoutMilliseconds)
.setSocketTimeout(this.socketTimeoutMilliseconds)
.setStaleConnectionCheckEnabled(false)
.setRedirectsEnabled(true).setMaxRedirects(maxRedirects)
.build();
HttpClientBuilder builder = HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig);
httpClient = builder
.setConnectionManager(poolingHttpClientConnectionManager)
.setKeepAliveStrategy(myStrategy).build();
if (reapInterval > 0 && idleConnectionsTimeout > 0) {
LOGGER.debug(String
.format("Initializing idle connection monitor thread with reap interval %s ms and idle connection time out %s ms",
reapInterval, idleConnectionsTimeout));
idcm = new IdleConnectionMonitorThread(
poolingHttpClientConnectionManager, reapInterval,
idleConnectionsTimeout);
idcm.start();
}
}