当前位置: 首页>>代码示例>>Java>>正文


Java MockWebServer.takeRequest方法代码示例

本文整理汇总了Java中okhttp3.mockwebserver.MockWebServer.takeRequest方法的典型用法代码示例。如果您正苦于以下问题:Java MockWebServer.takeRequest方法的具体用法?Java MockWebServer.takeRequest怎么用?Java MockWebServer.takeRequest使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在okhttp3.mockwebserver.MockWebServer的用法示例。


在下文中一共展示了MockWebServer.takeRequest方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: main

import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
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();
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:22,代码来源:JsonQueryParameters.java

示例2: testSendingCookiesFromStore

import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
@Test public void testSendingCookiesFromStore() throws Exception {
  MockWebServer server = new MockWebServer();
  server.enqueue(new MockResponse());
  server.start();
  HttpUrl serverUrl = urlWithIpAddress(server, "/");

  CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
  HttpCookie cookieA = new HttpCookie("a", "android");
  cookieA.setDomain(serverUrl.host());
  cookieA.setPath("/");
  cookieManager.getCookieStore().add(serverUrl.uri(), cookieA);
  HttpCookie cookieB = new HttpCookie("b", "banana");
  cookieB.setDomain(serverUrl.host());
  cookieB.setPath("/");
  cookieManager.getCookieStore().add(serverUrl.uri(), cookieB);
  client = client.newBuilder()
      .cookieJar(new JavaNetCookieJar(cookieManager))
      .build();

  get(serverUrl);
  RecordedRequest request = server.takeRequest();

  assertEquals("a=android; b=banana", request.getHeader("Cookie"));
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:25,代码来源:CookiesTest.java

示例3: receiveAndSendMultipleCookies

import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
@Test public void receiveAndSendMultipleCookies() throws Exception {
  MockWebServer server = new MockWebServer();
  server.enqueue(new MockResponse()
      .addHeader("Set-Cookie", "a=android")
      .addHeader("Set-Cookie", "b=banana"));
  server.enqueue(new MockResponse());
  server.start();

  CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
  client = client.newBuilder()
      .cookieJar(new JavaNetCookieJar(cookieManager))
      .build();

  get(urlWithIpAddress(server, "/"));
  RecordedRequest request1 = server.takeRequest();
  assertNull(request1.getHeader("Cookie"));

  get(urlWithIpAddress(server, "/"));
  RecordedRequest request2 = server.takeRequest();
  assertEquals("a=android; b=banana", request2.getHeader("Cookie"));
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:22,代码来源:CookiesTest.java

示例4: testCookiesSentIgnoresCase

import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
@Test public void testCookiesSentIgnoresCase() throws Exception {
  client = client.newBuilder()
      .cookieJar(new JavaNetCookieJar(new CookieManager() {
        @Override public Map<String, List<String>> get(URI uri,
            Map<String, List<String>> requestHeaders) throws IOException {
          Map<String, List<String>> result = new LinkedHashMap<>();
          result.put("COOKIE", Collections.singletonList("Bar=bar"));
          result.put("cooKIE2", Collections.singletonList("Baz=baz"));
          return result;
        }
      }))
      .build();

  MockWebServer server = new MockWebServer();
  server.enqueue(new MockResponse());
  server.start();

  get(server.url("/"));

  RecordedRequest request = server.takeRequest();
  assertEquals("Bar=bar; Baz=baz", request.getHeader("Cookie"));
  assertNull(request.getHeader("Cookie2"));
  assertNull(request.getHeader("Quux"));
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:25,代码来源:CookiesTest.java

示例5: assertPathsHaveBeenRequested

import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
private void assertPathsHaveBeenRequested(MockWebServer webServer, String... paths) throws InterruptedException {
    final List<String> expectedPaths = new ArrayList<>(paths.length);
    Collections.addAll(expectedPaths, paths);

    RecordedRequest request;

    while ((request = webServer.takeRequest(waitingTime, TimeUnit.MILLISECONDS)) != null) {
        if (!expectedPaths.remove(request.getPath())) {
            throw new AssertionError("Unknown path requested: " + request.getPath());
        }
    }

    if (!expectedPaths.isEmpty()) {
        throw new AssertionError("Expected paths not requested: " + expectedPaths);
    }
}
 
开发者ID:mozilla-mobile,项目名称:firefox-tv,代码行数:17,代码来源:WebViewDataTest.java

示例6: intercept

import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
@Test
public void intercept() throws Exception {

  MockWebServer mockWebServer = new MockWebServer();
  mockWebServer.start();
  mockWebServer.enqueue(new MockResponse());

  mockWebServer.enqueue(new MockResponse());

  OkHttpClient okHttpClient = new OkHttpClient()
      .newBuilder()
      .addInterceptor((Interceptor) new UserAgentInterceptor(USER_AGENT))
      .build();
  okHttpClient.newCall(new Request.Builder().url(mockWebServer.url("/")).build()).execute();

  RecordedRequest request = mockWebServer.takeRequest();
  assertEquals(USER_AGENT, request.getHeader("User-Agent"));
}
 
开发者ID:humaniq,项目名称:react-native-android-library-humaniq-api,代码行数:19,代码来源:UserAgentInterceptorTest.java

示例7: main

import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
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();
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:28,代码来源:ChunkingConverter.java

示例8: testRedirectsDoNotIncludeTooManyCookies

import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
@Test public void testRedirectsDoNotIncludeTooManyCookies() throws Exception {
  MockWebServer redirectTarget = new MockWebServer();
  redirectTarget.enqueue(new MockResponse().setBody("A"));
  redirectTarget.start();
  HttpUrl redirectTargetUrl = urlWithIpAddress(redirectTarget, "/");

  MockWebServer redirectSource = new MockWebServer();
  redirectSource.enqueue(new MockResponse()
      .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
      .addHeader("Location: " + redirectTargetUrl));
  redirectSource.start();
  HttpUrl redirectSourceUrl = urlWithIpAddress(redirectSource, "/");

  CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
  HttpCookie cookie = new HttpCookie("c", "cookie");
  cookie.setDomain(redirectSourceUrl.host());
  cookie.setPath("/");
  String portList = Integer.toString(redirectSource.getPort());
  cookie.setPortlist(portList);
  cookieManager.getCookieStore().add(redirectSourceUrl.uri(), cookie);
  client = client.newBuilder()
      .cookieJar(new JavaNetCookieJar(cookieManager))
      .build();

  get(redirectSourceUrl);
  RecordedRequest request = redirectSource.takeRequest();

  assertEquals("c=cookie", request.getHeader("Cookie"));

  for (String header : redirectTarget.takeRequest().getHeaders().names()) {
    if (header.startsWith("Cookie")) {
      fail(header);
    }
  }
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:36,代码来源:CookiesTest.java

示例9: MockNiFiS2SServer

import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
public MockNiFiS2SServer() throws IOException {
    mockWebServer = new MockWebServer();
    mockWebServer.start();
    requestAssertions = new ArrayList<>();

    siteToSitePeerListRequestAssertion = new RequestAssertion() {
        @Override
        public RecordedRequest check() throws Exception {
            RecordedRequest recordedRequest = mockWebServer.takeRequest();
            assertEquals(PeerTracker.NIFI_API_PATH + SITE_TO_SITE_PEERS_PATH, recordedRequest.getPath());
            return recordedRequest;
        }
    };
}
 
开发者ID:hortonworks,项目名称:nifi-android-s2s,代码行数:15,代码来源:MockNiFiS2SServer.java

示例10: testGetBalance

import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
@Test public void testGetBalance() throws IOException, InterruptedException {
  server = new MockWebServer();
  server.enqueue(new MockResponse().setBody("{"
      + "    \"success\": true,"
      + "    \"data\": {"
      + "        \"token\": {"
      + "            \"currency\": \"HMQ\","
      + "            \"amount\": 190.6"
      + "        },"
      + "        \"default\": {"
      + "            \"currency\": \"USD\","
      + "            \"amount\": 27.7323"
      + "        },"
      + "        \"local\": {"
      + "            \"currency\": \"SOS\","
      + "            \"amount\": 15141.841623783"
      + "        }"
      + "    }"
      + "}"));

  URL url = server.url("/").url();
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestProperty("Accept-Language", "en-US");
  InputStream in = connection.getInputStream();
  BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode());
  Balance balance = new Gson().fromJson(reader.readLine(), Balance.class);

  assertTrue(balance != null);

  RecordedRequest request = server.takeRequest();
  assertEquals("GET / HTTP/1.1", request.getRequestLine());
  assertEquals("en-US", request.getHeader("Accept-Language"));
  //System.out.println(server.takeRequest().);
}
 
开发者ID:humaniq,项目名称:react-native-android-library-humaniq-api,代码行数:36,代码来源:WalletMockWebTest.java

示例11: testWithClient

import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
@Test
public void testWithClient() throws IOException, InterruptedException {
    MockWebServer server = new MockWebServer();
    server.start();

    server.enqueue(new MockResponse()
            .setResponseCode(200)
            .setBody("{\"success\": true}")
    );

    String accessKey = "AKIDEXAMPLE";
    String secretKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY";
    String regionName = "us-east-1";
    String serviceName = "iam";

    ZonedDateTime aDate = ZonedDateTime.parse("2015-08-30T12:36:00.000Z", DateTimeFormatter.ISO_DATE_TIME);

    AwsConfiguration cfg = new AwsConfiguration(
            accessKey,
            secretKey,
            regionName,
            serviceName
    );

    Interceptor awsInterceptor = new AwsSigningInterceptor(cfg, () -> aDate);

    OkHttpClient client = new OkHttpClient.Builder()
            .addNetworkInterceptor(awsInterceptor)
            .build();

    Request.Builder req = createExampleRequest()
            .get()
            .url(server.url("/home/test"))
            .header("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")
            .header("User-Agent", "okhttp-client")
            .header("Accept", "application/json");

    Response res = client.newCall(req.build()).execute();

    RecordedRequest recordedRequest = server.takeRequest();

    String expected = "AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/us-east-1/iam/aws4_request, SignedHeaders=accept;accept-encoding;connection;content-type;host;user-agent;x-amz-date, Signature=12b929341232610f62ac811d95aa16f0b84d797382f609149068e4c065b7a01e";

    assertThat(recordedRequest.getHeader("Authorization")).isEqualTo(expected);
}
 
开发者ID:esiqveland,项目名称:okhttp-awssigner,代码行数:46,代码来源:AwsSigningInterceptorTest.java

示例12: testExternalVolumes

import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
@Test
public void testExternalVolumes() throws Exception {
    final MockWebServer server = new MockWebServer();
    final String mockResponse = "{\"container\": {\"volumes\": [" +
            "{\"containerPath\":\"/data/db\",\"mode\":\"RW\",\"external\":" +
            "{\"name\":\"mongodb-testvol\",\"provider\":\"dvdi\",\"options\":" +
            "{\"dvdi/driver\":\"rexray\"}}}]}}";

    try {
        server.enqueue(new MockResponse().setBody(mockResponse));
        server.start();
        Marathon client = MarathonClient.getInstance(server.url("/").toString());

        App app = new App();
        app.setId("mongo");
        app.setCpus(1.0);
        app.setMem(256.0);
        app.setContainer(new Container());
        app.getContainer().setDocker(new Docker());
        app.getContainer().getDocker().setImage("mongo");
        app.getContainer().setVolumes(new ArrayList<Volume>());

        ExternalVolume externalVolume = new ExternalVolume();
        externalVolume.setName("mongodb-testvol");
        externalVolume.setMode("RW");
        externalVolume.setContainerPath("/data/db");
        externalVolume.setProvider("dvdi");
        externalVolume.setDriver("rexray");

        app.getContainer().getVolumes().add(externalVolume);

        final App appRes = client.createApp(app);
        assertFalse(appRes.getContainer().getVolumes().isEmpty());

        ExternalVolume responseVolume = (ExternalVolume) appRes.getContainer().getVolumes().iterator().next();
        assertEquals("mongodb-testvol", responseVolume.getExternalVolumeInfo().getName());

        RecordedRequest request = server.takeRequest();
        assertNotNull(request);

        final String requestBody = request.getBody().readUtf8();
        assertNotNull(requestBody);

        // request to JSON
        JsonObject requestPayload = new Gson().fromJson(requestBody, JsonObject.class);
        assertNotNull(requestPayload);
        JsonObject requestVolume = requestPayload.getAsJsonObject("container").getAsJsonArray("volumes").get(0).getAsJsonObject();
        assertNotNull(requestVolume);
        assertEquals("RW", requestVolume.get("mode").getAsString());
        assertEquals("/data/db", requestVolume.get("containerPath").getAsString());
    } finally {
        server.shutdown();
    }
}
 
开发者ID:mesosphere,项目名称:marathon-client,代码行数:55,代码来源:ExternalVolumeTest.java


注:本文中的okhttp3.mockwebserver.MockWebServer.takeRequest方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。