Last active
January 6, 2022 15:37
-
-
Save Cepr0/fd5d9459f17da13b29126cf313328fe3 to your computer and use it in GitHub Desktop.
How to get all the headers from HttpServletRequest? - https://stackoverflow.com/a/49771639
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package io.github.cepr0.demo; | |
import org.junit.Before; | |
import org.junit.Test; | |
import org.springframework.http.HttpHeaders; | |
import javax.servlet.http.HttpServletRequest; | |
import java.util.*; | |
import java.util.function.Function; | |
import java.util.stream.Collectors; | |
import static org.assertj.core.api.Assertions.assertThat; | |
import static org.mockito.Mockito.mock; | |
import static org.mockito.Mockito.when; | |
public class HttpHeadersTest { | |
private HttpServletRequest httpRequest; | |
@SuppressWarnings("unchecked") | |
@Before | |
public void setUp() throws Exception { | |
httpRequest = mock(HttpServletRequest.class); | |
Enumeration headers = new StringTokenizer("header1 header2", " "); | |
when(httpRequest.getHeaderNames()).thenReturn(headers); | |
Enumeration header1Values = new StringTokenizer("value1_1 value1_2", " "); | |
when(httpRequest.getHeaders("header1")).thenReturn(header1Values); | |
Enumeration header2Values = new StringTokenizer("value2_1 value2_2", " "); | |
when(httpRequest.getHeaders("header2")).thenReturn(header2Values); | |
} | |
@Test | |
public void map() { | |
Map<String, List<String>> headersMap = Collections | |
.list(httpRequest.getHeaderNames()) | |
.stream() | |
.collect(Collectors.toMap( | |
Function.identity(), | |
h -> Collections.list(httpRequest.getHeaders(h)) | |
)); | |
assertThat(headersMap.get("header1")).containsOnly("value1_1", "value1_2"); | |
assertThat(headersMap.get("header2")).containsOnly("value2_1", "value2_2"); | |
} | |
@Test | |
public void httpHeaders() { | |
HttpHeaders httpHeaders = Collections | |
.list(httpRequest.getHeaderNames()) | |
.stream() | |
.collect(Collectors.toMap( | |
Function.identity(), | |
h -> Collections.list(httpRequest.getHeaders(h)), | |
(oldValue, newValue) -> newValue, | |
HttpHeaders::new | |
)); | |
assertThat(httpHeaders.get("header1")).containsOnly("value1_1", "value1_2"); | |
assertThat(httpHeaders.get("header2")).containsOnly("value2_1", "value2_2"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment