okhttp3.mockwebserver.MockWebServer.takeRequest()方法的使用及代码示例

x33g5p2x  于2022-01-24 转载在 其他  
字(12.6k)|赞(0)|评价(0)|浏览(132)

本文整理了Java中okhttp3.mockwebserver.MockWebServer.takeRequest()方法的一些代码示例,展示了MockWebServer.takeRequest()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。MockWebServer.takeRequest()方法的具体详情如下:
包路径:okhttp3.mockwebserver.MockWebServer
类名称:MockWebServer
方法名:takeRequest

MockWebServer.takeRequest介绍

[英]Awaits the next HTTP request, removes it, and returns it. Callers should use this to verify the request was sent as intended. This method will block until the request is available, possibly forever.
[中]等待下一个HTTP请求,将其删除并返回。呼叫者应使用此功能验证请求是否按预期发送。此方法将一直阻止,直到请求可用为止,可能是永远。

代码示例

代码示例来源:origin: spring-projects/spring-framework

private void expectRequest(Consumer<RecordedRequest> consumer) {
  try {
    consumer.accept(this.server.takeRequest());
  }
  catch (InterruptedException ex) {
    throw new IllegalStateException(ex);
  }
}

代码示例来源:origin: square/retrofit

public static void main(String... args) throws IOException, InterruptedException {
  MockWebServer server = new MockWebServer();
  server.start();
  server.enqueue(new MockResponse());

  Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(server.url("/"))
    .addConverterFactory(new JsonStringConverterFactory(GsonConverterFactory.create()))
    .build();
  Service service = retrofit.create(Service.class);

  Call<ResponseBody> call = service.example(new Filter("123"));
  Response<ResponseBody> response = call.execute();
  // TODO handle user response...

  // Print the request path that the server saw to show the JSON query param:
  RecordedRequest recordedRequest = server.takeRequest();
  System.out.println(recordedRequest.getPath());

  server.shutdown();
 }
}

代码示例来源:origin: square/retrofit

public static void main(String... args) throws IOException, InterruptedException {
  MockWebServer server = new MockWebServer();
  server.enqueue(new MockResponse());
  server.enqueue(new MockResponse());
  server.start();

  Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(server.url("/"))
    .addConverterFactory(new ChunkingConverterFactory())
    .addConverterFactory(GsonConverterFactory.create())
    .build();
  Service service = retrofit.create(Service.class);

  Repo retrofitRepo = new Repo("square", "retrofit");

  service.sendNormal(retrofitRepo).execute();
  RecordedRequest normalRequest = server.takeRequest();
  System.out.println(
    "Normal @Body Transfer-Encoding: " + normalRequest.getHeader("Transfer-Encoding"));

  service.sendChunked(retrofitRepo).execute();
  RecordedRequest chunkedRequest = server.takeRequest();
  System.out.println(
    "@Chunked @Body Transfer-Encoding: " + chunkedRequest.getHeader("Transfer-Encoding"));

  server.shutdown();
 }
}

代码示例来源:origin: SonarSource/sonarqube

private RecordedRequest takeAndVerifyPostRequest(String expectedPath) throws Exception {
 RecordedRequest request = server.takeRequest();
 assertThat(request.getMethod()).isEqualTo("POST");
 assertThat(request.getPath()).isEqualTo(expectedPath);
 assertThat(request.getHeader("User-Agent")).isEqualTo("SonarQube/6.2");
 return request;
}

代码示例来源:origin: SonarSource/sonarqube

private RecordedRequest call(OkHttpClient client) throws IOException, InterruptedException {
  server.enqueue(new MockResponse().setBody("pong"));
  client.newCall(new Request.Builder().url(server.url("/ping")).build()).execute();

  return server.takeRequest();
 }
}

代码示例来源:origin: bumptech/glide

@Test
public void testAppliesHeadersInGlideUrl() throws Exception {
 mockWebServer.enqueue(new MockResponse().setResponseCode(200));
 String headerField = "field";
 String headerValue = "value";
 Map<String, String> headersMap = new HashMap<>();
 headersMap.put(headerField, headerValue);
 Headers headers = mock(Headers.class);
 when(headers.getHeaders()).thenReturn(headersMap);
 getFetcher(headers).loadData(Priority.HIGH, callback);
 waitForResponseLatch.await();
 assertThat(mockWebServer.takeRequest().getHeader(headerField)).isEqualTo(headerValue);
}

代码示例来源:origin: bumptech/glide

@Test
public void testAppliesHeadersInGlideUrl() throws Exception {
 mockWebServer.enqueue(new MockResponse().setResponseCode(200));
 String headerField = "field";
 String headerValue = "value";
 Map<String, String> headersMap = new HashMap<>();
 headersMap.put(headerField, headerValue);
 Headers headers = mock(Headers.class);
 when(headers.getHeaders()).thenReturn(headersMap);
 getFetcher(headers).loadData(Priority.HIGH, callback);
 assertThat(mockWebServer.takeRequest().getHeader(headerField)).isEqualTo(headerValue);
}

代码示例来源:origin: bumptech/glide

@Test
public void testHandlesRedirect301s() throws Exception {
 String expected = "fakedata";
 mockWebServer.enqueue(new MockResponse().setResponseCode(301)
   .setHeader("Location", mockWebServer.url("/redirect").toString()));
 mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(expected));
 getFetcher().loadData(Priority.LOW, callback);
 verify(callback).onDataReady(streamCaptor.capture());
 TestUtil.assertStreamOf(expected, streamCaptor.getValue());
 assertThat(mockWebServer.takeRequest().getMethod()).isEqualTo("GET");
 assertThat(mockWebServer.takeRequest().getMethod()).isEqualTo("GET");
}

代码示例来源:origin: bumptech/glide

@Test
public void testHandlesRedirect302s() throws Exception {
 String expected = "fakedata";
 mockWebServer.enqueue(new MockResponse().setResponseCode(302)
   .setHeader("Location", mockWebServer.url("/redirect").toString()));
 mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(expected));
 getFetcher().loadData(Priority.LOW, callback);
 verify(callback).onDataReady(streamCaptor.capture());
 TestUtil.assertStreamOf(expected, streamCaptor.getValue());
 assertThat(mockWebServer.takeRequest().getMethod()).isEqualTo("GET");
 assertThat(mockWebServer.takeRequest().getMethod()).isEqualTo("GET");
}

代码示例来源:origin: bumptech/glide

@Test
public void testReturnsInputStreamOnStatusOk() throws Exception {
 String expected = "fakedata";
 mockWebServer.enqueue(new MockResponse().setBody(expected).setResponseCode(200));
 HttpUrlFetcher fetcher = getFetcher();
 fetcher.loadData(Priority.HIGH, callback);
 verify(callback).onDataReady(streamCaptor.capture());
 TestUtil.assertStreamOf(expected, streamCaptor.getValue());
 assertThat(mockWebServer.takeRequest().getMethod()).isEqualTo("GET");
}

代码示例来源:origin: bumptech/glide

@Test
public void testHandlesRelativeRedirects() throws Exception {
 String expected = "fakedata";
 mockWebServer
   .enqueue(new MockResponse().setResponseCode(301).setHeader("Location", "/redirect"));
 mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(expected));
 getFetcher().loadData(Priority.NORMAL, callback);
 verify(callback).onDataReady(streamCaptor.capture());
 TestUtil.assertStreamOf(expected, streamCaptor.getValue());
 RecordedRequest first = mockWebServer.takeRequest();
 assertThat(first.getMethod()).isEqualTo("GET");
 RecordedRequest second = mockWebServer.takeRequest();
 assertThat(second.getPath()).endsWith("/redirect");
 assertThat(second.getMethod()).isEqualTo("GET");
}

代码示例来源:origin: prestodb/presto

@Test
  public void testGetServerInfo()
      throws Exception
  {
    ServerInfo expected = new ServerInfo(UNKNOWN, "test", true, false, Optional.of(Duration.valueOf("2m")));

    server.enqueue(new MockResponse()
        .addHeader(CONTENT_TYPE, "application/json")
        .setBody(SERVER_INFO_CODEC.toJson(expected)));

    QueryExecutor executor = new QueryExecutor(new OkHttpClient());

    ServerInfo actual = executor.getServerInfo(server.url("/v1/info").uri());
    assertEquals(actual.getEnvironment(), "test");
    assertEquals(actual.getUptime(), Optional.of(Duration.valueOf("2m")));

    assertEquals(server.getRequestCount(), 1);
    assertEquals(server.takeRequest().getPath(), "/v1/info");
  }
}

代码示例来源:origin: bumptech/glide

@Test
public void testHandlesUpToFiveRedirects() throws Exception {
 int numRedirects = 4;
 String expected = "redirectedData";
 String redirectBase = "/redirect";
 for (int i = 0; i < numRedirects; i++) {
  mockWebServer.enqueue(new MockResponse().setResponseCode(301)
    .setHeader("Location", mockWebServer.url(redirectBase + i).toString()));
 }
 mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(expected));
 getFetcher().loadData(Priority.NORMAL, callback);
 waitForResponseLatch.await();
 verify(callback).onDataReady(streamCaptor.capture());
 assertStreamOf(expected, streamCaptor.getValue());
 assertThat(mockWebServer.takeRequest().getPath()).contains(DEFAULT_PATH);
 for (int i = 0; i < numRedirects; i++) {
  assertThat(mockWebServer.takeRequest().getPath()).contains(redirectBase + i);
 }
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void add_headers_to_GET_request() throws Exception {
 answerHelloWorld();
 GetRequest request = new GetRequest("api/issues/search")
  .setHeader("X-Foo", "fooz")
  .setHeader("X-Bar", "barz");
 underTest = HttpConnector.newBuilder().url(serverUrl).build();
 underTest.call(request);
 RecordedRequest recordedRequest = server.takeRequest();
 assertThat(recordedRequest.getHeader("X-Foo")).isEqualTo("fooz");
 assertThat(recordedRequest.getHeader("X-Bar")).isEqualTo("barz");
}

代码示例来源:origin: bumptech/glide

@Test
public void testHandlesUpToFiveRedirects() throws Exception {
 int numRedirects = 4;
 String expected = "redirectedData";
 String redirectBase = "/redirect";
 for (int i = 0; i < numRedirects; i++) {
  mockWebServer.enqueue(new MockResponse().setResponseCode(301)
    .setHeader("Location", mockWebServer.url(redirectBase + i).toString()));
 }
 mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(expected));
 getFetcher().loadData(Priority.NORMAL, callback);
 verify(callback).onDataReady(streamCaptor.capture());
 TestUtil.assertStreamOf(expected, streamCaptor.getValue());
 RecordedRequest request = mockWebServer.takeRequest();
 assertThat(request.getPath()).contains(DEFAULT_PATH);
 assertThat(request.getMethod()).isEqualTo("GET");
 for (int i = 0; i < numRedirects; i++) {
  RecordedRequest current = mockWebServer.takeRequest();
  assertThat(current.getPath()).contains(redirectBase + i);
  assertThat(current.getMethod()).isEqualTo("GET");
 }
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void add_header_to_POST_request() throws Exception {
 answerHelloWorld();
 PostRequest request = new PostRequest("api/issues/search")
  .setHeader("X-Foo", "fooz")
  .setHeader("X-Bar", "barz");
 underTest = HttpConnector.newBuilder().url(serverUrl).build();
 underTest.call(request);
 RecordedRequest recordedRequest = server.takeRequest();
 assertThat(recordedRequest.getHeader("X-Foo")).isEqualTo("fooz");
 assertThat(recordedRequest.getHeader("X-Bar")).isEqualTo("barz");
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void send_user_agent() throws Exception {
 answerHelloWorld();
 underTest = HttpConnector.newBuilder()
  .url(serverUrl)
  .userAgent("Maven Plugin/2.3")
  .build();
 underTest.call(new GetRequest("api/issues/search"));
 RecordedRequest recordedRequest = server.takeRequest();
 assertThat(recordedRequest.getHeader("User-Agent")).isEqualTo("Maven Plugin/2.3");
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void getTokenResponseWhenClientAuthenticationBasicThenAuthorizationHeaderIsSent() throws Exception {
  String accessTokenSuccessResponse = "{\n" +
      "	\"access_token\": \"access-token-1234\",\n" +
      "   \"token_type\": \"bearer\",\n" +
      "   \"expires_in\": \"3600\"\n" +
      "}\n";
  this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
  this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest());
  RecordedRequest recordedRequest = this.server.takeRequest();
  assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void use_basic_authentication_with_null_password() throws Exception {
 answerHelloWorld();
 underTest = HttpConnector.newBuilder()
  .url(serverUrl)
  .credentials("theLogin", null)
  .build();
 GetRequest request = new GetRequest("api/issues/search");
 underTest.call(request);
 RecordedRequest recordedRequest = server.takeRequest();
 assertThat(recordedRequest.getHeader("Authorization")).isEqualTo(basic("theLogin", ""));
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void use_basic_authentication() throws Exception {
 answerHelloWorld();
 underTest = HttpConnector.newBuilder()
  .url(serverUrl)
  .credentials("theLogin", "thePassword")
  .build();
 GetRequest request = new GetRequest("api/issues/search");
 underTest.call(request);
 RecordedRequest recordedRequest = server.takeRequest();
 assertThat(recordedRequest.getHeader("Authorization")).isEqualTo(basic("theLogin", "thePassword"));
}

相关文章