Skip to content

Commit

Permalink
Merge pull request #346 from LukasLohoff/105-support-custom-headers
Browse files Browse the repository at this point in the history
Allow custom headers for http requests
  • Loading branch information
LukasLohoff authored Mar 29, 2019
2 parents 6a0ec89 + 19445d7 commit d12cecb
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ public class MutableHttpServletRequest extends HttpServletRequestWrapper {
*/
private Map<String, String[]> customParameters;

/**
* Holds custom header mapping
*/
private Map<String, String> customHeaders;

/**
*
*/
Expand All @@ -61,6 +66,7 @@ public MutableHttpServletRequest(HttpServletRequest request) {
this.customRequestURI = request.getRequestURI();
this.customParameters = new HashMap<String, String[]>(
request.getParameterMap());
this.customHeaders = new HashMap<String, String>();
}

/**
Expand Down Expand Up @@ -205,6 +211,17 @@ public void setParameter(String key, String value) {
this.addParameter(key, value);
}

/**
* @param key The header name (without a trailing colon `:`)
* @param value The header value
*/
public void setHeader(String key, String value) {
if (!StringUtils.isEmpty(this.getHeader(key))) {
this.removeHeader(key);
}
customHeaders.put(key, value);
}

/**
* @param key
* @param value
Expand All @@ -231,6 +248,15 @@ public void removeParameter(String key) {
}
}

/**
* @param key
*/
public void removeHeader(String key) {
if (customHeaders.get(key) != null) {
customHeaders.remove(key);
}
}

/**
*
*/
Expand All @@ -252,6 +278,19 @@ public Map<String, String[]> getParameterMap() {
return customParameters;
}

/**
*
*/
@Override
public String getHeader(String name) {
String headerValue = customHeaders.get(name);
// Check custom headers first
if (headerValue != null){
return headerValue;
}
return ((HttpServletRequest) getRequest()).getHeader(name);
}

/**
*
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ public class MutableHttpServletRequestTest {

private static final String CUSTOM_REQUEST_PARAMETER_VALUE = "Kagawa";

private static final String CUSTOM_REQUEST_HEADER_KEY = "Authorization";

private static final String CUSTOM_REQUEST_HEADER_VALUE = "U2hpbmppOkthZ2F3YQ==";

private MutableHttpServletRequest mutableRequest;

@Before
Expand Down Expand Up @@ -89,6 +93,12 @@ public void add_query_parameter_array() {
mutableRequest.getParameter(CUSTOM_REQUEST_PARAMETER_KEY));
}

@Test
public void set_custom_header() {
mutableRequest.setHeader(CUSTOM_REQUEST_HEADER_KEY, CUSTOM_REQUEST_HEADER_VALUE);
assertEquals(CUSTOM_REQUEST_HEADER_VALUE, mutableRequest.getHeader(CUSTOM_REQUEST_HEADER_KEY));
}

@Test
public void get_parameter_map() {
Map<String, String[]> params = mutableRequest.getParameterMap();
Expand Down

0 comments on commit d12cecb

Please sign in to comment.