@Test public void authenticate() throws Exception {
server.enqueue(new MockResponse()
.setResponseCode(HttpURLConnection.HTTP_UNAUTHORIZED)
.addHeader("www-authenticate: Basic realm=\"protected area\"")
.setBody("Please authenticate."));
server.enqueue(new MockResponse()
.setBody("Successful auth!"));
String credential = Credentials.basic("username", "password");
client = client.newBuilder()
.authenticator(new RecordingOkAuthenticator(credential))
.build();
Call call = client.newCall(new Request.Builder()
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals("Successful auth!", response.body().string());
RecordedRequest denied = server.takeRequest();
assertNull(denied.getHeader("Authorization"));
RecordedRequest accepted = server.takeRequest();
assertEquals("GET / HTTP/1.1", accepted.getRequestLine());
assertEquals(credential, accepted.getHeader("Authorization"));
}
java类okhttp3.mockwebserver.RecordedRequest的实例源码
HttpOverHttp2Test.java 文件源码
项目:GitHub
阅读 20
收藏 0
点赞 0
评论 0
URLConnectionTest.java 文件源码
项目:GitHub
阅读 36
收藏 0
点赞 0
评论 0
/**
* We had a bug where we attempted to gunzip responses that didn't have a body. This only came up
* with 304s since that response code can include headers (like "Content-Encoding") without any
* content to go along with it. https://github.com/square/okhttp/issues/358
*/
@Test public void noTransparentGzipFor304NotModified() throws Exception {
server.enqueue(new MockResponse()
.clearHeaders()
.setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)
.addHeader("Content-Encoding: gzip"));
server.enqueue(new MockResponse().setBody("b"));
HttpURLConnection connection1 = urlFactory.open(server.url("/").url());
assertEquals(HttpURLConnection.HTTP_NOT_MODIFIED, connection1.getResponseCode());
assertContent("", connection1);
HttpURLConnection connection2 = urlFactory.open(server.url("/").url());
assertEquals(HttpURLConnection.HTTP_OK, connection2.getResponseCode());
assertContent("b", connection2);
RecordedRequest requestA = server.takeRequest();
assertEquals(0, requestA.getSequenceNumber());
RecordedRequest requestB = server.takeRequest();
assertEquals(1, requestB.getSequenceNumber());
}
ResponseCacheTest.java 文件源码
项目:GitHub
阅读 26
收藏 0
点赞 0
评论 0
@Test public void redirectToCachedResult() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Cache-Control: max-age=60")
.setBody("ABC"));
server.enqueue(new MockResponse()
.setResponseCode(HttpURLConnection.HTTP_MOVED_PERM)
.addHeader("Location: /foo"));
server.enqueue(new MockResponse()
.setBody("DEF"));
assertEquals("ABC", readAscii(openConnection(server.url("/foo").url())));
RecordedRequest request1 = server.takeRequest();
assertEquals("GET /foo HTTP/1.1", request1.getRequestLine());
assertEquals(0, request1.getSequenceNumber());
assertEquals("ABC", readAscii(openConnection(server.url("/bar").url())));
RecordedRequest request2 = server.takeRequest();
assertEquals("GET /bar HTTP/1.1", request2.getRequestLine());
assertEquals(1, request2.getSequenceNumber());
// an unrelated request should reuse the pooled connection
assertEquals("DEF", readAscii(openConnection(server.url("/baz").url())));
RecordedRequest request3 = server.takeRequest();
assertEquals("GET /baz HTTP/1.1", request3.getRequestLine());
assertEquals(2, request3.getSequenceNumber());
}
CookiesTest.java 文件源码
项目:GitHub
阅读 16
收藏 0
点赞 0
评论 0
@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"));
}
CallTest.java 文件源码
项目:GitHub
阅读 25
收藏 0
点赞 0
评论 0
@Test public void put() throws Exception {
server.enqueue(new MockResponse().setBody("abc"));
Request request = new Request.Builder()
.url(server.url("/"))
.put(RequestBody.create(MediaType.parse("text/plain"), "def"))
.build();
executeSynchronously(request)
.assertCode(200)
.assertBody("abc");
RecordedRequest recordedRequest = server.takeRequest();
assertEquals("PUT", recordedRequest.getMethod());
assertEquals("def", recordedRequest.getBody().readUtf8());
assertEquals("3", recordedRequest.getHeader("Content-Length"));
assertEquals("text/plain; charset=utf-8", recordedRequest.getHeader("Content-Type"));
}
JsonQueryParameters.java 文件源码
项目:GitHub
阅读 23
收藏 0
点赞 0
评论 0
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();
}
UrlConnectionCacheTest.java 文件源码
项目:GitHub
阅读 18
收藏 0
点赞 0
评论 0
@Test public void redirectToCachedResult() throws Exception {
server.enqueue(new MockResponse().addHeader("Cache-Control: max-age=60").setBody("ABC"));
server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_PERM)
.addHeader("Location: /foo"));
server.enqueue(new MockResponse().setBody("DEF"));
assertEquals("ABC", readAscii(urlFactory.open(server.url("/foo").url())));
RecordedRequest request1 = server.takeRequest();
assertEquals("GET /foo HTTP/1.1", request1.getRequestLine());
assertEquals(0, request1.getSequenceNumber());
assertEquals("ABC", readAscii(urlFactory.open(server.url("/bar").url())));
RecordedRequest request2 = server.takeRequest();
assertEquals("GET /bar HTTP/1.1", request2.getRequestLine());
assertEquals(1, request2.getSequenceNumber());
// an unrelated request should reuse the pooled connection
assertEquals("DEF", readAscii(urlFactory.open(server.url("/baz").url())));
RecordedRequest request3 = server.takeRequest();
assertEquals("GET /baz HTTP/1.1", request3.getRequestLine());
assertEquals(2, request3.getSequenceNumber());
}
URLConnectionTest.java 文件源码
项目:GitHub
阅读 22
收藏 0
点赞 0
评论 0
private void doUpload(TransferKind uploadKind, WriteKind writeKind) throws Exception {
int n = 512 * 1024;
server.setBodyLimit(0);
server.enqueue(new MockResponse());
HttpURLConnection conn = urlFactory.open(server.url("/").url());
conn.setDoOutput(true);
conn.setRequestMethod("POST");
if (uploadKind == TransferKind.CHUNKED) {
conn.setChunkedStreamingMode(-1);
} else {
conn.setFixedLengthStreamingMode(n);
}
OutputStream out = conn.getOutputStream();
if (writeKind == WriteKind.BYTE_BY_BYTE) {
for (int i = 0; i < n; ++i) {
out.write('x');
}
} else {
byte[] buf = new byte[writeKind == WriteKind.SMALL_BUFFERS ? 256 : 64 * 1024];
Arrays.fill(buf, (byte) 'x');
for (int i = 0; i < n; i += buf.length) {
out.write(buf, 0, Math.min(buf.length, n - i));
}
}
out.close();
assertEquals(200, conn.getResponseCode());
RecordedRequest request = server.takeRequest();
assertEquals(n, request.getBodySize());
if (uploadKind == TransferKind.CHUNKED) {
assertTrue(request.getChunkSizes().size() > 0);
} else {
assertTrue(request.getChunkSizes().isEmpty());
}
}
URLConnectionTest.java 文件源码
项目:GitHub
阅读 25
收藏 0
点赞 0
评论 0
private void testResponseRedirectedWithPost(int redirectCode, TransferKind transferKind)
throws Exception {
server.enqueue(new MockResponse().setResponseCode(redirectCode)
.addHeader("Location: /page2")
.setBody("This page has moved!"));
server.enqueue(new MockResponse().setBody("Page 2"));
connection = urlFactory.open(server.url("/page1").url());
connection.setDoOutput(true);
transferKind.setForRequest(connection, 4);
byte[] requestBody = {'A', 'B', 'C', 'D'};
OutputStream outputStream = connection.getOutputStream();
outputStream.write(requestBody);
outputStream.close();
assertEquals("Page 2", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
assertTrue(connection.getDoOutput());
RecordedRequest page1 = server.takeRequest();
assertEquals("POST /page1 HTTP/1.1", page1.getRequestLine());
assertEquals("ABCD", page1.getBody().readUtf8());
RecordedRequest page2 = server.takeRequest();
assertEquals("GET /page2 HTTP/1.1", page2.getRequestLine());
}
CookiesTest.java 文件源码
项目:GitHub
阅读 29
收藏 0
点赞 0
评论 0
@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"));
}
CookiesTest.java 文件源码
项目:GitHub
阅读 25
收藏 0
点赞 0
评论 0
@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"));
}
CallTest.java 文件源码
项目:GitHub
阅读 29
收藏 0
点赞 0
评论 0
@Test public void deleteWithRequestBody() throws Exception {
server.enqueue(new MockResponse().setBody("abc"));
Request request = new Request.Builder()
.url(server.url("/"))
.method("DELETE", RequestBody.create(MediaType.parse("text/plain"), "def"))
.build();
executeSynchronously(request)
.assertCode(200)
.assertBody("abc");
RecordedRequest recordedRequest = server.takeRequest();
assertEquals("DELETE", recordedRequest.getMethod());
assertEquals("def", recordedRequest.getBody().readUtf8());
}
CallTest.java 文件源码
项目:GitHub
阅读 24
收藏 0
点赞 0
评论 0
@Test public void requestCookies() throws Exception {
server.enqueue(new MockResponse());
RecordingCookieJar cookieJar = new RecordingCookieJar();
cookieJar.enqueueRequestCookies(
new Cookie.Builder().name("a").value("b").domain(server.getHostName()).build(),
new Cookie.Builder().name("c").value("d").domain(server.getHostName()).build());
client = client.newBuilder()
.cookieJar(cookieJar)
.build();
executeSynchronously("/").assertCode(200);
RecordedRequest recordedRequest = server.takeRequest();
assertEquals("a=b; c=d", recordedRequest.getHeader("Cookie"));
}
CookiesTest.java 文件源码
项目:GitHub
阅读 16
收藏 0
点赞 0
评论 0
@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"));
}
APIClientTest.java 文件源码
项目:Guardian.java
阅读 15
收藏 0
点赞 0
评论 0
@Test
public void shouldStartFlow() throws Exception {
server.jsonResponse(MockServer.START_FLOW_VALID, 201);
StartFlowResponse startFlowResponse = apiClient
.startFlow(ENROLLMENT_TICKET)
.execute();
RecordedRequest recordedRequest = server.takeRequest();
assertThat(recordedRequest, hasMethodAndPath("POST", "/api/start-flow"));
assertThat(recordedRequest, hasHeader("Content-Type", "application/json; charset=utf-8"));
assertThat(recordedRequest, hasHeader("Authorization", "Ticket id=\"ENROLLMENT_TICKET\""));
Map<String, Object> body = bodyFromRequest(recordedRequest);
assertThat(body, hasEntry("state_transport", (Object) "polling"));
assertThat(startFlowResponse.getTransactionToken(), is(equalTo("THE_TRANSACTION_TOKEN")));
assertThat(startFlowResponse.getDeviceAccount(), is(notNullValue()));
assertThat(startFlowResponse.getDeviceAccount().getId(), is(equalTo("THE_ENROLLMENT_ID")));
assertThat(startFlowResponse.getDeviceAccount().getStatus(), is(equalTo("confirmation_pending")));
assertThat(startFlowResponse.getDeviceAccount().getOtpSecret(), is(equalTo("THE_OTP_SECRET")));
assertThat(startFlowResponse.getDeviceAccount().getRecoveryCode(), is(equalTo("THE_RECOVERY_CODE")));
}
CallTest.java 文件源码
项目:GitHub
阅读 28
收藏 0
点赞 0
评论 0
@Test public void deleteWithRequestBody() throws Exception {
server.enqueue(new MockResponse().setBody("abc"));
Request request = new Request.Builder()
.url(server.url("/"))
.method("DELETE", RequestBody.create(MediaType.parse("text/plain"), "def"))
.build();
executeSynchronously(request)
.assertCode(200)
.assertBody("abc");
RecordedRequest recordedRequest = server.takeRequest();
assertEquals("DELETE", recordedRequest.getMethod());
assertEquals("def", recordedRequest.getBody().readUtf8());
}
CallTest.java 文件源码
项目:GitHub
阅读 23
收藏 0
点赞 0
评论 0
@Test public void requestBodyRetransmittedOnClientRequestTimeout() throws Exception {
enqueueRequestTimeoutResponses();
Response response = client.newCall(new Request.Builder()
.url(server.url("/"))
.post(RequestBody.create(MediaType.parse("text/plain"), "Hello"))
.build()).execute();
assertEquals("Body", response.body().string());
RecordedRequest request1 = server.takeRequest();
assertEquals("Hello", request1.getBody().readUtf8());
RecordedRequest request2 = server.takeRequest();
assertEquals("Hello", request2.getBody().readUtf8());
}
CallTest.java 文件源码
项目:GitHub
阅读 32
收藏 0
点赞 0
评论 0
@Test public void propfindRedirectsToPropfindAndMaintainsRequestBody() throws Exception {
// given
server.enqueue(new MockResponse()
.setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
.addHeader("Location: /page2")
.setBody("This page has moved!"));
server.enqueue(new MockResponse().setBody("Page 2"));
// when
Response response = client.newCall(new Request.Builder()
.url(server.url("/page1"))
.method("PROPFIND", RequestBody.create(MediaType.parse("text/plain"), "Request Body"))
.build()).execute();
// then
assertEquals("Page 2", response.body().string());
RecordedRequest page1 = server.takeRequest();
assertEquals("PROPFIND /page1 HTTP/1.1", page1.getRequestLine());
assertEquals("Request Body", page1.getBody().readUtf8());
RecordedRequest page2 = server.takeRequest();
assertEquals("PROPFIND /page2 HTTP/1.1", page2.getRequestLine());
assertEquals("Request Body", page2.getBody().readUtf8());
}
DataGateUserTemplateTest.java 文件源码
项目:nitrite-database
阅读 18
收藏 0
点赞 0
评论 0
@Test
public void testCreateRemoteUser() throws JsonProcessingException, InterruptedException {
UserAccount userAccount = new UserAccount();
userAccount.setUserName("test");
userAccount.setPassword("password");
userAccount.setCollections(new ArrayList<String>() {{ add("collection"); }});
userAccount.setAuthorities(new String[]{ "USER" });
MockResponse response = new MockResponse()
.addHeader("Content-Type", "application/json; charset=utf-8")
.setResponseCode(201)
.setBody("{}");
server.enqueue(response);
dataGateUserTemplate.createRemoteUser(userAccount);
RecordedRequest recordedRequest = server.takeRequest();
assertEquals(recordedRequest.getRequestLine(), "POST /datagate/api/v1/user/create HTTP/1.1");
}
CallTest.java 文件源码
项目:GitHub
阅读 24
收藏 0
点赞 0
评论 0
@Test public void canceledBeforeResponseReadSignalsOnFailure() throws Exception {
Request requestA = new Request.Builder().url(server.url("/a")).build();
final Call call = client.newCall(requestA);
server.setDispatcher(new Dispatcher() {
@Override public MockResponse dispatch(RecordedRequest request) {
call.cancel();
return new MockResponse().setBody("A");
}
});
call.enqueue(callback);
assertEquals("/a", server.takeRequest().getPath());
callback.await(requestA.url()).assertFailure("Canceled", "stream was reset: CANCEL",
"Socket closed");
}
URLConnectionTest.java 文件源码
项目:GitHub
阅读 25
收藏 0
点赞 0
评论 0
/**
* We had a bug where we weren't closing Gzip streams on redirects.
* https://github.com/square/okhttp/issues/441
*/
@Test public void gzipWithRedirectAndConnectionReuse() throws Exception {
server.enqueue(new MockResponse()
.setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
.addHeader("Location: /foo")
.addHeader("Content-Encoding: gzip")
.setBody(gzip("Moved! Moved! Moved!")));
server.enqueue(new MockResponse().setBody("This is the new page!"));
HttpURLConnection connection = urlFactory.open(server.url("/").url());
assertContent("This is the new page!", connection);
RecordedRequest requestA = server.takeRequest();
assertEquals(0, requestA.getSequenceNumber());
RecordedRequest requestB = server.takeRequest();
assertEquals(1, requestB.getSequenceNumber());
}
HttpTransactionTest.java 文件源码
项目:nifi-android-s2s
阅读 15
收藏 0
点赞 0
评论 0
private List<RecordedRequest> performTestSuccessfulTransaction(SiteToSiteClientConfig siteToSiteClientConfig) throws Exception {
String transactionPath = mockNiFiS2SServer.enqueuCreateTransaction(portIdentifier, transactionIdentifier, 30);
mockNiFiS2SServer.enqueueTtlExtension(transactionPath);
List<DataPacket> dataPackets = Arrays.<DataPacket>asList(new ByteArrayDataPacket(new HashMap<String, String>(), "testMessage".getBytes(Charsets.UTF_8)));
mockNiFiS2SServer.enqueuDataPackets(transactionPath, dataPackets, siteToSiteClientConfig);
mockNiFiS2SServer.enqueueTransactionComplete(transactionPath, dataPackets.size(), ResponseCode.CONFIRM_TRANSACTION, ResponseCode.CONFIRM_TRANSACTION);
HttpTransaction httpTransaction = new HttpTransaction(new HttpPeerConnector(mockNiFiS2SServer.getNifiApiUrl(), siteToSiteClientConfig, new SiteToSiteRemoteCluster()), portIdentifier, siteToSiteClientConfig, scheduledThreadPoolExecutor);
scheduledThreadPoolExecutor.getTtlExtender(15).run();
for (DataPacket dataPacket : dataPackets) {
httpTransaction.send(dataPacket);
}
httpTransaction.confirm();
httpTransaction.complete();
return mockNiFiS2SServer.verifyAssertions();
}
CallTest.java 文件源码
项目:GitHub
阅读 31
收藏 0
点赞 0
评论 0
@Test public void serverRespondsWithUnsolicited100Continue() throws Exception {
server.enqueue(new MockResponse()
.setStatus("HTTP/1.1 100 Continue"));
Request request = new Request.Builder()
.url(server.url("/"))
.post(RequestBody.create(MediaType.parse("text/plain"), "abc"))
.build();
Call call = client.newCall(request);
Response response = call.execute();
assertEquals(100, response.code());
assertEquals("Continue", response.message());
assertEquals("", response.body().string());
RecordedRequest recordedRequest = server.takeRequest();
assertEquals("abc", recordedRequest.getBody().readUtf8());
}
HttpOverHttp2Test.java 文件源码
项目:GitHub
阅读 26
收藏 0
点赞 0
评论 0
@Test public void sendRequestCookies() throws Exception {
RecordingCookieJar cookieJar = new RecordingCookieJar();
Cookie requestCookie = new Cookie.Builder()
.name("a")
.value("b")
.domain(server.getHostName())
.build();
cookieJar.enqueueRequestCookies(requestCookie);
client = client.newBuilder()
.cookieJar(cookieJar)
.build();
server.enqueue(new MockResponse());
Call call = client.newCall(new Request.Builder()
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals("", response.body().string());
RecordedRequest request = server.takeRequest();
assertEquals("a=b", request.getHeader("Cookie"));
}
URLConnectionTest.java 文件源码
项目:GitHub
阅读 23
收藏 0
点赞 0
评论 0
@Test public void redirectedOnHttps() throws IOException, InterruptedException {
server.useHttps(sslClient.socketFactory, false);
server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
.addHeader("Location: /foo")
.setBody("This page has moved!"));
server.enqueue(new MockResponse().setBody("This is the new location!"));
urlFactory.setClient(urlFactory.client().newBuilder()
.sslSocketFactory(sslClient.socketFactory, sslClient.trustManager)
.hostnameVerifier(new RecordingHostnameVerifier())
.build());
connection = urlFactory.open(server.url("/").url());
assertEquals("This is the new location!",
readAscii(connection.getInputStream(), Integer.MAX_VALUE));
RecordedRequest first = server.takeRequest();
assertEquals("GET / HTTP/1.1", first.getRequestLine());
RecordedRequest retry = server.takeRequest();
assertEquals("GET /foo HTTP/1.1", retry.getRequestLine());
assertEquals("Expected connection reuse", 1, retry.getSequenceNumber());
}
HttpOverHttp2Test.java 文件源码
项目:GitHub
阅读 20
收藏 0
点赞 0
评论 0
/** https://github.com/square/okhttp/issues/3103 */
@Test public void domainFronting() throws Exception {
client = client.newBuilder()
.addNetworkInterceptor(new Interceptor() {
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder()
.header("Host", "privateobject.com")
.build();
return chain.proceed(request);
}
})
.build();
server.enqueue(new MockResponse());
Call call = client.newCall(new Request.Builder()
.url(server.url("/"))
.build());
Response response = call.execute();
assertEquals("", response.body().string());
RecordedRequest recordedRequest = server.takeRequest();
assertEquals("privateobject.com", recordedRequest.getHeader(":authority"));
}
URLConnectionTest.java 文件源码
项目:GitHub
阅读 23
收藏 0
点赞 0
评论 0
@Test public void veryLargeFixedLengthRequest() throws Exception {
server.setBodyLimit(0);
server.enqueue(new MockResponse());
connection = urlFactory.open(server.url("/").url());
connection.setDoOutput(true);
long contentLength = Integer.MAX_VALUE + 1L;
connection.setFixedLengthStreamingMode(contentLength);
OutputStream out = connection.getOutputStream();
byte[] buffer = new byte[1024 * 1024];
for (long bytesWritten = 0; bytesWritten < contentLength; ) {
int byteCount = (int) Math.min(buffer.length, contentLength - bytesWritten);
out.write(buffer, 0, byteCount);
bytesWritten += byteCount;
}
assertContent("", connection);
RecordedRequest request = server.takeRequest();
assertEquals(Long.toString(contentLength), request.getHeader("Content-Length"));
}
CacheTest.java 文件源码
项目:GitHub
阅读 22
收藏 0
点赞 0
评论 0
private RecordedRequest assertClientSuppliedCondition(MockResponse seed, String conditionName,
String conditionValue) throws Exception {
server.enqueue(seed.setBody("A"));
server.enqueue(new MockResponse()
.setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED));
HttpUrl url = server.url("/");
assertEquals("A", get(url).body().string());
Request request = new Request.Builder()
.url(url)
.header(conditionName, conditionValue)
.build();
Response response = client.newCall(request).execute();
assertEquals(HttpURLConnection.HTTP_NOT_MODIFIED, response.code());
assertEquals("", response.body().string());
server.takeRequest(); // seed
return server.takeRequest();
}
DataGateUserTemplateTest.java 文件源码
项目:nitrite-database
阅读 14
收藏 0
点赞 0
评论 0
@Test
public void testUpdateRemoteUser() throws JsonProcessingException, InterruptedException {
UserAccount userAccount = new UserAccount();
userAccount.setUserName("test");
userAccount.setPassword("password");
userAccount.setCollections(new ArrayList<String>() {{ add("collection"); }});
userAccount.setAuthorities(new String[]{ "USER" });
MockResponse response = new MockResponse()
.addHeader("Content-Type", "application/json; charset=utf-8")
.setResponseCode(200)
.setBody("{}");
server.enqueue(response);
dataGateUserTemplate.updateRemoteUser(userAccount);
RecordedRequest recordedRequest = server.takeRequest();
assertEquals(recordedRequest.getRequestLine(), "PUT /datagate/api/v1/user/update HTTP/1.1");
}
WebSocketHttpTest.java 文件源码
项目:GitHub
阅读 19
收藏 0
点赞 0
评论 0
/**
* There's no read timeout when reading the first byte of a new frame. But as soon as we start
* reading a frame we enable the read timeout. In this test we have the server returning the first
* byte of a frame but no more frames.
*/
@Test public void readTimeoutAppliesWithinFrames() throws IOException {
webServer.setDispatcher(new Dispatcher() {
@Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
return upgradeResponse(request)
.setBody(new Buffer().write(ByteString.decodeHex("81"))) // Truncated frame.
.removeHeader("Content-Length")
.setSocketPolicy(SocketPolicy.KEEP_OPEN);
}
});
WebSocket webSocket = newWebSocket();
clientListener.assertOpen();
clientListener.assertFailure(SocketTimeoutException.class, "timeout");
assertFalse(webSocket.close(1000, null));
}