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


Java MockWebServer.enqueue方法代碼示例

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


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

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

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

示例3: before

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

    MockResponse response = new MockResponse();
    response.setBody(RESPONSE_BODY);
    server.enqueue(response);

    retrofit = new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(new TimedCallAdapterFactory(metrics))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .baseUrl(server.url("/").toString())
            .build();
}
 
開發者ID:cvent,項目名稱:retrofit-metrics,代碼行數:18,代碼來源:TimedCallAdapterFactoryTest.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: 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\": \"Jason\"}"));
  server.enqueue(new MockResponse().setBody("<user name=\"Eximel\"/>"));

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

  User user1 = service.exampleJson().execute().body();
  System.out.println("User 1: " + user1.name);

  User user2 = service.exampleXml().execute().body();
  System.out.println("User 2: " + user2.name);

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

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

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

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

示例9: testNetscapeResponse

import okhttp3.mockwebserver.MockWebServer; //導入方法依賴的package包/類
@Test
public void testNetscapeResponse() 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; "
      + "expires=Fri, 31-Dec-9999 23:59:59 GMT; "
      + "path=/path; "
      + "domain=" + urlWithIpAddress.host() + "; "
      + "secure"));
  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(null, cookie.getComment());
  assertEquals(null, cookie.getCommentURL());
  assertEquals(false, cookie.getDiscard());
  assertTrue(cookie.getMaxAge() > 100000000000L);
  assertEquals("/path", cookie.getPath());
  assertEquals(true, cookie.getSecure());
  assertEquals(0, cookie.getVersion());
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:31,代碼來源:CookiesTest.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();

  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

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

示例13: 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.start();
    } catch (IOException e) {
        throw new AssertionError("Could not start web server", e);
    }
}
 
開發者ID:mozilla-mobile,項目名稱:firefox-tv,代碼行數:28,代碼來源:SwitchContextTest.java

示例14: setup

import okhttp3.mockwebserver.MockWebServer; //導入方法依賴的package包/類
@Before
public void setup() throws IOException, TimeoutException {
	mDevice = UiDevice.getInstance(getInstrumentation());

	server = new MockWebServer();
	server.start();
	String serverUrl = server.url("").toString();

	server.enqueue(TestHelper.getResponseForRaw(R.raw.conferences_json));
	server.enqueue(TestHelper.getResponseForRaw(R.raw.conferences_101_33c3_json));

	Intent i = new Intent();
	i.putExtra("server_url",serverUrl);
	mActivityTestRule.launchActivity(i);
}
 
開發者ID:NiciDieNase,項目名稱:chaosflix,代碼行數:16,代碼來源:ConferencesActivityTest.java

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


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