Java Code Examples for okhttp3.mockwebserver.RecordedRequest#getHeaders()

The following examples show how to use okhttp3.mockwebserver.RecordedRequest#getHeaders() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RequestMatchers.java    From RESTMock with Apache License 2.0 6 votes vote down vote up
/**
 * Checks whether matched request contains non-null headers with given names
 *
 * @param headerNames names of headers to match
 * @return A new {@link RequestMatcher} object that will match {@link RecordedRequest} if it
 * contains specified header names
 */
public static RequestMatcher hasHeaderNames(final String... headerNames) {
    return new RequestMatcher("has headers: " + Arrays.toString(headerNames)) {

        @Override
        protected boolean matchesSafely(RecordedRequest item) {
            if (headerNames == null) {
                throw new IllegalArgumentException("You did not specify any header names");
            }
            if (headerNames.length > 0 && item.getHeaders() == null) {
                return false;
            }
            for (String header : headerNames) {
                if (item.getHeader(header) == null) {
                    return false;
                }
            }
            return true;
        }
    };
}
 
Example 2
Source File: ClientTest.java    From contentful.java with Apache License 2.0 6 votes vote down vote up
@Test @Enqueue
public void usingCustomCallFactoryDoesNotAddDefaultHeaders() throws InterruptedException {
  final Call.Factory callFactory = new OkHttpClient.Builder().build();

  createBuilder()
      .setSpace(DEFAULT_SPACE)
      .setCallFactory(callFactory)
      .build()
      .fetchSpace();

  assertThat(server.getRequestCount()).isEqualTo(1);

  final RecordedRequest recordedRequest = server.takeRequest();
  final Headers headers = recordedRequest.getHeaders();

  assertThat(headers.size()).isEqualTo(4);

  assertThat(headers.get(AuthorizationHeaderInterceptor.HEADER_NAME)).isNull();
  assertThat(headers.get(UserAgentHeaderInterceptor.HEADER_NAME)).startsWith("okhttp");
}
 
Example 3
Source File: NoMatchersForRequestException.java    From requestmatcher with Apache License 2.0 5 votes vote down vote up
private static StringBuilder buildRequestMessage(final StringBuilder sb,
                                                 final RecordedRequest request) {

    sb.append("> ").append(request.getRequestLine());

    final Headers headers = request.getHeaders();
    for (int i = 0, count = headers.size(); i < count; i++) {
        sb.append("\n> ").append(headers.name(i)).append(": ").append(headers.value(i));
    }

    final String body = request.getBody().clone().readUtf8();
    return body.isEmpty() ? sb : sb.append("\n\n").append(body);
}
 
Example 4
Source File: GeoApiContextTest.java    From google-maps-services-java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testGetIncludesDefaultUserAgent() throws Exception {
  // Set up a mock request
  ApiResponse<Object> fakeResponse = mock(ApiResponse.class);
  String path = "/";
  Map<String, List<String>> params = new HashMap<>();
  params.put("key", Collections.singletonList("value"));

  // Set up the fake web server
  server.enqueue(new MockResponse());
  server.start();
  setMockBaseUrl();

  // Build & execute the request using our context
  builder.build().get(new ApiConfig(path), fakeResponse.getClass(), params).awaitIgnoreError();

  // Read the headers
  server.shutdown();
  RecordedRequest request = server.takeRequest();
  Headers headers = request.getHeaders();
  boolean headerFound = false;
  for (String headerName : headers.names()) {
    if (headerName.equals("User-Agent")) {
      headerFound = true;
      String headerValue = headers.get(headerName);
      assertTrue(
          "User agent not in correct format",
          headerValue.matches("GoogleGeoApiClientJava/[^\\s]+"));
    }
  }

  assertTrue("User agent header not present", headerFound);
}
 
Example 5
Source File: HttpIT.java    From digdag with Apache License 2.0 4 votes vote down vote up
@Test
public void testCustomHeaders()
        throws Exception
{
    String uri = "http://localhost:" + httpMockWebServer.getPort() + "/test";
    runWorkflow(folder, "acceptance/http/http_headers.dig",
            ImmutableMap.of(
                    "test_uri", uri
            ),
            ImmutableMap.of(
                    "secrets.header_value_1", "secret_header_value_1",
                    "secrets.header_name_2", "secret_header_name_2",
                    "secrets.header_value_2", "secret_header_value_2"
            ));
    assertThat(httpMockWebServer.getRequestCount(), is(1));
    RecordedRequest request = httpMockWebServer.takeRequest();

    Headers h = request.getHeaders();

    // Find first "foo" header
    int i = 0;
    for (; i < h.size() && !h.name(i).equals("foo"); i++) {
    }
    assertThat(i, is(lessThan(h.size())));

    // Verify header ordering
    assertThat(h.name(i), is("foo"));
    assertThat(h.value(i), is("foo-value-1"));

    assertThat(h.name(i + 1), is("bar"));
    assertThat(h.value(i + 1), is("bar-value"));

    assertThat(h.name(i + 2), is("foo"));
    assertThat(h.value(i + 2), is("foo-value-2"));

    assertThat(h.name(i + 3), is("plain_header_name_1"));
    assertThat(h.value(i + 3), is("secret_header_value_1"));

    assertThat(h.name(i + 4), is("secret_header_name_2"));
    assertThat(h.value(i + 4), is("secret_header_value_2"));
}
 
Example 6
Source File: ClientTest.java    From contentful.java with Apache License 2.0 3 votes vote down vote up
@Test @Enqueue
public void notUsingCustomCallFactoryDoesCreateCallFactoryWithAuthAndUserAgentInterceptors() throws InterruptedException {

  createClient().fetchSpace();

  final RecordedRequest recordedRequest = server.takeRequest();
  final Headers headers = recordedRequest.getHeaders();

  assertThat(headers.size()).isEqualTo(6);

  assertThat(headers.get(AuthorizationHeaderInterceptor.HEADER_NAME)).endsWith(DEFAULT_TOKEN);
  assertThat(headers.get(UserAgentHeaderInterceptor.HEADER_NAME)).startsWith("contentful.java");
}