本文整理汇总了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"));
}
示例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;
}
示例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"));
}
示例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"));
}
示例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));
}
示例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);
}
}
示例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();
}
示例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);
}
示例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);
}
示例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();
}
示例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
}
示例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
}
示例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.");
}
}
示例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());
}
示例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();
}