下面列出了怎么用org.apache.http.HeaderElement的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Validates that response <b>header</b> contains expected <b>attributes</b>.
* <p>
* <b>Actions performed at this step:</b>
* </p>
* <ul>
* <li>Checks that HTTP response header contains expected attributes.</li>
* </ul>
* @param httpHeaderName HTTP header name. For example, <b>Content-Type</b>
* @param attributes expected HTTP header attributes. For example, <b>charset=utf-8</b>
*/
@Then("response header '$httpHeaderName' contains attribute: $attributes")
public void assertHeaderContainsAttributes(String httpHeaderName, ExamplesTable attributes)
{
performIfHttpResponseIsPresent(response ->
{
getHeaderByName(response, httpHeaderName).ifPresent(header ->
{
List<String> actualAttributes = Stream.of(header.getElements()).map(HeaderElement::getName)
.collect(Collectors.toList());
for (Parameters row : attributes.getRowsAsParameters(true))
{
String expectedAttribute = row.valueAs("attribute", String.class);
softAssert.assertThat(httpHeaderName + " header contains " + expectedAttribute + " attribute",
actualAttributes, contains(expectedAttribute));
}
});
});
}
@Test
void testGetHeaderAttributes()
{
mockHttpResponse();
Header header = mock(Header.class);
when(header.getName()).thenReturn(SET_COOKIES_HEADER_NAME);
httpResponse.setResponseHeaders(header);
HeaderElement headerElement = mock(HeaderElement.class);
when(header.getElements()).thenReturn(new HeaderElement[] { headerElement });
when(softAssert.assertTrue(SET_COOKIES_HEADER_NAME + HEADER_IS_PRESENT, true)).thenReturn(true);
String headerAttributeName = "HTTPOnly";
when(headerElement.getName()).thenReturn(headerAttributeName);
ExamplesTable attribute = new ExamplesTable("|attribute|\n|HTTPOnly|/|");
httpResponseValidationSteps.assertHeaderContainsAttributes(SET_COOKIES_HEADER_NAME, attribute);
verify(softAssert).assertThat(
eq(SET_COOKIES_HEADER_NAME + " header contains " + headerAttributeName + " attribute"),
eq(Collections.singletonList(headerAttributeName)),
argThat(matcher -> matcher.toString().equals(Matchers.contains(headerAttributeName).toString())));
}
@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;
}
@Test
public void testHandle() throws IOException {
HttpResponse response = mock(HttpResponse.class);
StatusLine statusLine = mock(StatusLine.class);
HttpEntity entity = mock(HttpEntity.class);
Logger log = mock(Logger.class);
Header header = mock(Header.class);
expect(response.getStatusLine()).andReturn(statusLine).once();
expect(statusLine.getStatusCode()).andReturn(HttpStatus.SC_OK).once();
expect(response.getEntity()).andReturn(entity).times(2);
final ByteArrayInputStream bais = new ByteArrayInputStream("yolo".getBytes());
expect(entity.getContent()).andReturn(bais).times(2);
expect(entity.getContentType()).andReturn(header).times(1);
expect(header.getElements()).andReturn(new HeaderElement[]{});
expect(entity.getContentLength()).andReturn(4L).times(2);
log.warn("yolo");
expectLastCall().once();
replay(response, statusLine, entity, header, log);
KsqlVersionCheckerResponseHandler kvcr = new KsqlVersionCheckerResponseHandler(log);
kvcr.handle(response);
verify(response, statusLine, entity, header, log);
}
private String extractToken(CloseableHttpResponse response) throws ZaasClientException, IOException {
String token = "";
int httpResponseCode = response.getStatusLine().getStatusCode();
if (httpResponseCode == 204) {
HeaderElement[] elements = response.getHeaders("Set-Cookie")[0].getElements();
Optional<HeaderElement> apimlAuthCookie = Stream.of(elements)
.filter(element -> element.getName().equals(COOKIE_PREFIX))
.findFirst();
if (apimlAuthCookie.isPresent()) {
token = apimlAuthCookie.get().getValue();
}
} else {
String obtainedMessage = EntityUtils.toString(response.getEntity());
if (httpResponseCode == 401) {
throw new ZaasClientException(ZaasClientErrorCodes.INVALID_AUTHENTICATION, obtainedMessage);
} else if (httpResponseCode == 400) {
throw new ZaasClientException(ZaasClientErrorCodes.EMPTY_NULL_USERNAME_PASSWORD, obtainedMessage);
} else {
throw new ZaasClientException(ZaasClientErrorCodes.GENERIC_EXCEPTION, obtainedMessage);
}
}
return token;
}
@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 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;
}
@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;
}
private static boolean contentTypeIs(HttpResponse response, String contentType) {
Header[] headers = response.getHeaders("Content-Type");
if (headers.length == 0) {
return false;
}
for (Header header : headers) {
for (HeaderElement element : header.getElements()) {
String name = element.getName().split("\\+")[0];
if (contentType.equals(name)) {
return true;
}
}
}
return false;
}
/**
* 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;
}
};
}
@Test
public void valid() {
Header[] headers = {new Header() {
public String getName() {
return "session_id";
}
public String getValue() {
return "12345";
}
public HeaderElement[] getElements() throws ParseException {
return new HeaderElement[0];
}
}};
ApiClientResponse response = new ApiClientResponse(headers, "{\"key\":\"value\"}");
assertEquals("12345", response.getHeader("session_id"));
assertEquals("{\n \"key\" : \"value\"\n}", response.toJson());
assertEquals("value", response.getField("key"));
}
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;
}
private void addMockedHeader(
final HttpResponse httpResponseMock,
final String name,
final String value,
HeaderElement[] elements) {
final Header header = new Header() {
@Override
public String getName() {
return name;
}
@Override
public String getValue() {
return value;
}
@Override
public HeaderElement[] getElements() throws ParseException {
return elements;
}
};
when(httpResponseMock.getFirstHeader(name)).thenReturn(header);
}
private HttpResponse httpResponse(String sessionIdInResult, String version) throws IOException {
final HttpResponse httpResponseMock = mock(HttpResponse.class);
StatusLine statusLineMock = mock(StatusLine.class);
when(httpResponseMock.getStatusLine()).thenReturn(statusLineMock);
when(statusLineMock.getStatusCode()).thenReturn(200);
addMockedHeader(httpResponseMock, Headers.SESSION_ID, sessionIdInResult, null);
addMockedHeader(httpResponseMock, Headers.VERSION, version, null);
HeaderElement[] headerElements = new HeaderElement[1];
headerElements[0] = mock(HeaderElement.class);
final HttpEntity httpEntityMock = mock(HttpEntity.class);
when(httpResponseMock.getEntity()).thenReturn(httpEntityMock);
final InputStream inputs = new ByteArrayInputStream("fake response data".getBytes());
when(httpEntityMock.getContent()).thenReturn(inputs);
return httpResponseMock;
}
@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;
}
@Test
public void createCookieForHeaderElementTest() {
String cookiePath = "/client/api";
String paramName = "paramName1";
String paramValue = "paramVale1";
NameValuePair[] parameters = new NameValuePair[1];
parameters[0] = new BasicNameValuePair(paramName, paramValue);
String headerName = "headerElementName";
String headerValue = "headerElementValue";
HeaderElement headerElement = new BasicHeaderElement(headerName, headerValue, parameters);
Mockito.doNothing().when(apacheCloudStackClient).configureDomainForCookie(Mockito.any(BasicClientCookie.class));
BasicClientCookie cookieForHeaderElement = apacheCloudStackClient.createCookieForHeaderElement(headerElement);
Assert.assertNotNull(cookieForHeaderElement);
Assert.assertEquals(headerName, cookieForHeaderElement.getName());
Assert.assertEquals(headerValue, cookieForHeaderElement.getValue());
Assert.assertEquals(paramValue, cookieForHeaderElement.getAttribute(paramName));
Assert.assertEquals(cookiePath, cookieForHeaderElement.getPath());
Mockito.verify(apacheCloudStackClient).configureDomainForCookie(Mockito.eq(cookieForHeaderElement));
}
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;
}
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;
}
@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;
};
}
static private String getContentCharSet(final HttpEntity entity)
throws ParseException {
if (entity == null) {
throw new IllegalArgumentException("entity may not be null");
}
String charset = null;
if (entity.getContentType() != null) {
HeaderElement values[] = entity.getContentType().getElements();
if (values.length > 0) {
NameValuePair param = values[0].getParameterByName("charset");
if (param != null) {
charset = param.getValue();
}
}
}
return charset;
}
protected String getAttachmentFileName(org.apache.http.HttpResponse resp) {
String fileName = null;
Header[] contentDisp = resp.getHeaders("content-disposition");
if (contentDisp != null && contentDisp.length > 0) {
HeaderElement[] headerElements = contentDisp[0].getElements();
if (headerElements != null) {
for (HeaderElement headerElement : headerElements) {
if ("attachment".equals(headerElement.getName())) {
NameValuePair param = headerElement.getParameterByName("filename");
if (param != null) {
fileName = param.getValue();
break;
}
}
}
}
}
return fileName;
}
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";
}
/**
* copy: EntityUtils Obtains character set of the entity, if known.
*
* @param entity must not be null
* @return the character set, or null if not found
* @throws ParseException if header elements cannot be parsed
* @throws IllegalArgumentException if entity is null
*/
private static String getContentCharSet(final HttpEntity entity) throws ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity must not be null");
}
String charset = null;
if (entity.getContentType() != null) {
HeaderElement values[] = entity.getContentType().getElements();
if (values.length > 0) {
NameValuePair param = values[0].getParameterByName("charset");
if (param != null) {
charset = param.getValue();
}
}
}
return charset;
}
@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 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;
}
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;
}