當前位置: 首頁>>代碼示例>>Java>>正文


Java MockWebServer.start方法代碼示例

本文整理匯總了Java中okhttp3.mockwebserver.MockWebServer.start方法的典型用法代碼示例。如果您正苦於以下問題:Java MockWebServer.start方法的具體用法?Java MockWebServer.start怎麽用?Java MockWebServer.start使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在okhttp3.mockwebserver.MockWebServer的用法示例。


在下文中一共展示了MockWebServer.start方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: 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

示例2: startServer

import okhttp3.mockwebserver.MockWebServer; //導入方法依賴的package包/類
private MockWebServer startServer() throws IOException {
  Logger.getLogger(MockWebServer.class.getName()).setLevel(Level.WARNING);
  MockWebServer server = new MockWebServer();

  if (tls) {
    SslClient sslClient = SslClient.localhost();
    server.useHttps(sslClient.socketFactory, false);
    server.setProtocols(protocols);
  }

  final MockResponse response = newResponse();
  server.setDispatcher(new Dispatcher() {
    @Override public MockResponse dispatch(RecordedRequest request) {
      return response;
    }
  });

  server.start();
  return server;
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:21,代碼來源:Benchmark.java

示例3: 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

示例4: 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

示例5: testSetsReadTimeout

import okhttp3.mockwebserver.MockWebServer; //導入方法依賴的package包/類
@Test
public void testSetsReadTimeout() throws Exception {
  MockWebServer tempWebServer = new MockWebServer();
  tempWebServer.enqueue(
      new MockResponse().setBody("test").throttleBody(1, TIMEOUT_TIME_MS, TimeUnit.MILLISECONDS));
  tempWebServer.start();

  try {
    getFetcher().loadData(Priority.HIGH, callback);
  } finally {
    tempWebServer.shutdown();
    // shutdown() called before any enqueue() blocks until it times out.
    mockWebServer.enqueue(new MockResponse().setResponseCode(200));
  }

  verify(callback).onLoadFailed(isA(IOException.class));
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:18,代碼來源:HttpUrlFetcherServerTest.java

示例6: beforeActivityLaunched

import okhttp3.mockwebserver.MockWebServer; //導入方法依賴的package包/類
@Override
protected void beforeActivityLaunched() {
    super.beforeActivityLaunched();

    appContext = InstrumentationRegistry.getInstrumentation()
            .getTargetContext()
            .getApplicationContext();

    PreferenceManager.getDefaultSharedPreferences(appContext)
            .edit()
            .putBoolean(FIRSTRUN_PREF, true)
            .apply();

    webServer = new MockWebServer();

    try {
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("image_test.html"))
                .addHeader("Set-Cookie", "sphere=battery; Expires=Wed, 21 Oct 2035 07:28:00 GMT;"));
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("rabbit.jpg")));
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("download.jpg")));
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("rabbit.jpg")));

        webServer.start();
    } catch (IOException e) {
        throw new AssertionError("Could not start web server", e);
    }
}
 
開發者ID:mozilla-mobile,項目名稱:firefox-tv,代碼行數:32,代碼來源:ImageSelectTest.java

示例7: beforeEachTest

import okhttp3.mockwebserver.MockWebServer; //導入方法依賴的package包/類
@Before public void beforeEachTest() throws Exception {
  mockWebServer = new MockWebServer();
  mockWebServer.start();

  // Set the apps url to the local mock server
  DependencyInjection.BASE_URL = mockWebServer.url("").toString();
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:8,代碼來源:HomePresenterTest.java

示例8: setUp

import okhttp3.mockwebserver.MockWebServer; //導入方法依賴的package包/類
@Before
public void setUp() throws Exception {
  server = new MockWebServer();
  server.start();

  final String mockedUrl = server
      .url("/")
      .toString();

  client = new CameraClient(mockedUrl);
}
 
開發者ID:mariobodemann,項目名稱:osc,代碼行數:12,代碼來源:CameraClientTest.java

示例9: setUp

import okhttp3.mockwebserver.MockWebServer; //導入方法依賴的package包/類
@Before
public void setUp() throws IOException {
  MockitoAnnotations.initMocks(this);

  waitForResponseLatch = new CountDownLatch(1);
  doAnswer(new CountDown()).when(callback).onDataReady(any(InputStream.class));
  doAnswer(new CountDown()).when(callback).onLoadFailed(any(Exception.class));
  requestQueue = Volley.newRequestQueue(RuntimeEnvironment.application);
  mockWebServer = new MockWebServer();
  mockWebServer.start();

  streamCaptor = ArgumentCaptor.forClass(InputStream.class);
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:14,代碼來源:VolleyStreamFetcherServerTest.java

示例10: 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

示例11: assertCached

import okhttp3.mockwebserver.MockWebServer; //導入方法依賴的package包/類
private void assertCached(boolean shouldPut, int responseCode) throws Exception {
  int expectedResponseCode = responseCode;

  server = new MockWebServer();
  MockResponse mockResponse = new MockResponse()
      .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
      .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
      .setResponseCode(responseCode)
      .setBody("ABCDE")
      .addHeader("WWW-Authenticate: challenge");
  if (responseCode == HttpURLConnection.HTTP_PROXY_AUTH) {
    mockResponse.addHeader("Proxy-Authenticate: Basic realm=\"protected area\"");
  } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
    mockResponse.addHeader("WWW-Authenticate: Basic realm=\"protected area\"");
  } else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT
      || responseCode == HttpURLConnection.HTTP_RESET) {
    mockResponse.setBody(""); // We forbid bodies for 204 and 205.
  }
  server.enqueue(mockResponse);

  if (responseCode == HttpURLConnection.HTTP_CLIENT_TIMEOUT) {
    // 408's are a bit of an outlier because we may repeat the request if we encounter this
    // response code. In this scenario, there are 2 responses: the initial 408 and then the 200
    // because of the retry. We just want to ensure the initial 408 isn't cached.
    expectedResponseCode = 200;
    server.enqueue(new MockResponse()
        .setHeader("Cache-Control", "no-store")
        .setBody("FGHIJ"));
  }

  server.start();

  URL url = server.url("/").url();
  HttpURLConnection connection = openConnection(url);
  assertEquals(expectedResponseCode, connection.getResponseCode());

  // Exhaust the content stream.
  readAscii(connection);

  CacheResponse cached = cache.get(url.toURI(), "GET", null);
  if (shouldPut) {
    assertNotNull(Integer.toString(responseCode), cached);
  } else {
    assertNull(Integer.toString(responseCode), cached);
  }
  server.shutdown(); // tearDown() isn't sufficient; this test starts multiple servers
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:48,代碼來源:ResponseCacheTest.java

示例12: assertCached

import okhttp3.mockwebserver.MockWebServer; //導入方法依賴的package包/類
private void assertCached(boolean shouldPut, int responseCode) throws Exception {
  int expectedResponseCode = responseCode;

  server = new MockWebServer();
  MockResponse mockResponse = new MockResponse()
      .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
      .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
      .setResponseCode(responseCode)
      .setBody("ABCDE")
      .addHeader("WWW-Authenticate: challenge");
  if (responseCode == HttpURLConnection.HTTP_PROXY_AUTH) {
    mockResponse.addHeader("Proxy-Authenticate: Basic realm=\"protected area\"");
  } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
    mockResponse.addHeader("WWW-Authenticate: Basic realm=\"protected area\"");
  } else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT
      || responseCode == HttpURLConnection.HTTP_RESET) {
    mockResponse.setBody(""); // We forbid bodies for 204 and 205.
  }
  server.enqueue(mockResponse);

  if (responseCode == HttpURLConnection.HTTP_CLIENT_TIMEOUT) {
    // 408's are a bit of an outlier because we may repeat the request if we encounter this
    // response code. In this scenario, there are 2 responses: the initial 408 and then the 200
    // because of the retry. We just want to ensure the initial 408 isn't cached.
    expectedResponseCode = 200;
    server.enqueue(new MockResponse()
        .setHeader("Cache-Control", "no-store")
        .setBody("FGHIJ"));
  }

  server.start();

  Request request = new Request.Builder()
      .url(server.url("/"))
      .build();
  Response response = client.newCall(request).execute();
  assertEquals(expectedResponseCode, response.code());

  // Exhaust the content stream.
  response.body().string();

  Response cached = cache.get(request);
  if (shouldPut) {
    assertNotNull(Integer.toString(responseCode), cached);
    cached.body().close();
  } else {
    assertNull(Integer.toString(responseCode), cached);
  }
  server.shutdown(); // tearDown() isn't sufficient; this test starts multiple servers
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:51,代碼來源:CacheTest.java

示例13: startMockWebServer

import okhttp3.mockwebserver.MockWebServer; //導入方法依賴的package包/類
/**
 * Start mock web server for the wikipedia api.
 *
 * @return {@link MockWebServer}
 */
private MockWebServer startMockWebServer() {
    try {
        MockWebServer mockWebServer = new MockWebServer();
        mockWebServer.start();
        WikiHelper.BASE_WIKI_URL = mockWebServer.url("/").toString();
        return mockWebServer;
    } catch (IOException e) {
        e.printStackTrace();
        fail("Failed to startTimeMills mock server.");
        throw new RuntimeException("Failed to startTimeMills mock server.");
    }
}
 
開發者ID:kevalpatel2106,項目名稱:smart-lens,代碼行數:18,代碼來源:InfoActivityTest.java

示例14: testQuotedAttributeValues

import okhttp3.mockwebserver.MockWebServer; //導入方法依賴的package包/類
@Test public void testQuotedAttributeValues() throws Exception {
  CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
  client = client.newBuilder()
      .cookieJar(new JavaNetCookieJar(cookieManager))
      .build();
  MockWebServer server = new MockWebServer();
  server.start();

  HttpUrl urlWithIpAddress = urlWithIpAddress(server, "/path/foo");
  server.enqueue(new MockResponse().addHeader("Set-Cookie: a=\"android\"; "
      + "Comment=\"this cookie is delicious\"; "
      + "CommentURL=\"http://google.com/\"; "
      + "Discard; "
      + "Domain=" + urlWithIpAddress.host() + "; "
      + "Max-Age=60; "
      + "Path=\"/path\"; "
      + "Port=\"80,443," + server.getPort() + "\"; "
      + "Secure; "
      + "Version=\"1\""));
  get(urlWithIpAddress);

  List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
  assertEquals(1, cookies.size());
  HttpCookie cookie = cookies.get(0);
  assertEquals("a", cookie.getName());
  assertEquals("android", cookie.getValue());
  assertEquals(60.0, cookie.getMaxAge(), 1.0); // Converting to a fixed date can cause rounding!
  assertEquals("/path", cookie.getPath());
  assertEquals(true, cookie.getSecure());
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:31,代碼來源:CookiesTest.java

示例15: main

import okhttp3.mockwebserver.MockWebServer; //導入方法依賴的package包/類
public static void main(String... args) throws IOException {
  MockWebServer server = new MockWebServer();
  server.start();
  server.enqueue(new MockResponse().setBody("{\"name\": \"Moshi\"}"));
  server.enqueue(new MockResponse().setBody("{\"name\": \"Gson\"}"));
  server.enqueue(new MockResponse().setBody("<user name=\"SimpleXML\"/>"));
  server.enqueue(new MockResponse().setBody("{\"name\": \"Gson\"}"));

  com.squareup.moshi.Moshi moshi = new com.squareup.moshi.Moshi.Builder().build();
  com.google.gson.Gson gson = new GsonBuilder().create();
  MoshiConverterFactory moshiConverterFactory = MoshiConverterFactory.create(moshi);
  GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create(gson);
  SimpleXmlConverterFactory simpleXmlConverterFactory = SimpleXmlConverterFactory.create();
  Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/"))
      .addConverterFactory(
          new AnnotatedConverterFactory.Builder().add(Moshi.class, moshiConverterFactory)
              .add(Gson.class, gsonConverterFactory)
              .add(SimpleXml.class, simpleXmlConverterFactory)
              .build())
      .addConverterFactory(gsonConverterFactory)
      .build();
  Service service = retrofit.create(Service.class);

  Library library1 = service.exampleMoshi().execute().body();
  System.out.println("Library 1: " + library1.name);

  Library library2 = service.exampleGson().execute().body();
  System.out.println("Library 2: " + library2.name);

  Library library3 = service.exampleSimpleXml().execute().body();
  System.out.println("Library 3: " + library3.name);

  Library library4 = service.exampleDefault().execute().body();
  System.out.println("Library 4: " + library4.name);

  server.shutdown();
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:38,代碼來源:AnnotatedConverters.java


注:本文中的okhttp3.mockwebserver.MockWebServer.start方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。