Merge pull request #12549 from anuragkumawat/JAVA-13614

JAVA-13614 Look into How to Read HTTP Headers in Spring REST Controllers article
This commit is contained in:
kwoyke 2022-07-31 21:57:54 +02:00 committed by GitHub
commit a07425cc49
2 changed files with 21 additions and 3 deletions

View File

@ -1,6 +1,8 @@
package com.baeldung.spring.headers.controller;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;
@ -24,9 +26,10 @@ public class ReadHeaderRestController {
}
@GetMapping("/greeting")
public ResponseEntity<String> greeting(@RequestHeader(value = "accept-language") String language) {
public ResponseEntity<String> greeting(@RequestHeader(value = HttpHeaders.ACCEPT_LANGUAGE) String language) {
String greeting = "";
String firstLanguage = (language.length() > 1 ? language.substring(0, 2) : language);
List<Locale.LanguageRange> ranges = Locale.LanguageRange.parse(language);
String firstLanguage = ranges.get(0).getRange();
switch (firstLanguage) {
case "es":
greeting = "Hola!";

View File

@ -10,6 +10,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
import org.springframework.test.web.servlet.MockMvc;
@ -51,11 +52,25 @@ public class ReadHeaderRestControllerIntegrationTest {
@Test
public void whenGetRequestSentToGreeting_thenStatusOKAndGreetingReturned() throws Exception {
mockMvc.perform(get("/greeting").header("accept-language", "de"))
mockMvc.perform(get("/greeting").header(HttpHeaders.ACCEPT_LANGUAGE, "de"))
.andExpect(status().isOk())
.andExpect(content().string("Hallo!"));
}
@Test
public void whenPrioritizedListGetRequestSentToGreeting_thenStatusOKAndGreetingReturned() throws Exception {
mockMvc.perform(get("/greeting").header(HttpHeaders.ACCEPT_LANGUAGE, "fr,en,de"))
.andExpect(status().isOk())
.andExpect(content().string("Bonjour!"));
}
@Test
public void whenWeightedListGetRequestSentToGreeting_thenStatusOKAndGreetingReturned() throws Exception {
mockMvc.perform(get("/greeting").header(HttpHeaders.ACCEPT_LANGUAGE, "Accept-Language: es; q=1.0, de; q=0.5"))
.andExpect(status().isOk())
.andExpect(content().string("Hola!"));
}
@Test
public void whenGetRequestSentToDouble_thenStatusOKAndCorrectResultReturned() throws Exception {
mockMvc.perform(get("/double").header("my-number", 2))