diff --git a/okhttp-tests/src/test/java/okhttp3/HeadersTest.java b/okhttp-tests/src/test/java/okhttp3/HeadersTest.java index 0dfcee31b97f..8480bac638b4 100644 --- a/okhttp-tests/src/test/java/okhttp3/HeadersTest.java +++ b/okhttp-tests/src/test/java/okhttp3/HeadersTest.java @@ -343,6 +343,20 @@ public final class HeadersTest { assertEquals("A: a\nB: bb\n", headers.toString()); } + @Test public void headersAddAll() { + Headers sourceHeaders = new Headers.Builder() + .add("A", "aa") + .add("a", "aa") + .add("B", "bb") + .build(); + Headers headers = new Headers.Builder() + .add("A", "a") + .addAll(sourceHeaders) + .add("C", "c") + .build(); + assertEquals("A: a\nA: aa\na: aa\nB: bb\nC: c\n", headers.toString()); + } + /** See https://github.com/square/okhttp/issues/2780. */ @Test public void testDigestChallenges() { // Strict RFC 2617 header. diff --git a/okhttp/src/main/java/okhttp3/Headers.java b/okhttp/src/main/java/okhttp3/Headers.java index d5ef33aa7092..67834bd701c2 100644 --- a/okhttp/src/main/java/okhttp3/Headers.java +++ b/okhttp/src/main/java/okhttp3/Headers.java @@ -283,12 +283,26 @@ public Builder add(String line) { return add(line.substring(0, index).trim(), line.substring(index + 1)); } - /** Add a field with the specified value. */ + /** + * Add a header with the specified name and value. Does validation of header names and values. + */ public Builder add(String name, String value) { checkNameAndValue(name, value); return addLenient(name, value); } + /** + * Adds all headers from an existing collection. Does validation of header names and values. + */ + public Builder addAll(Headers headers) { + int size = headers.size(); + for (int i = 0; i < size; i++) { + addLenient(headers.name(i), headers.value(i)); + } + + return this; + } + /** * Add a field with the specified value without any validation. Only appropriate for headers * from the remote peer or cache.