Search in sources :

Example 16 with MockWebServer

use of okhttp3.mockwebserver.MockWebServer in project okhttp by square.

the class Benchmark method run.

@ArbitraryMeasurement(description = "requests per second")
public double run() throws Exception {
    if (VERBOSE)
        System.out.println(toString());
    HttpClient httpClient = client.create();
    // Prepare the client & server
    httpClient.prepare(this);
    MockWebServer server = startServer();
    HttpUrl url = server.url("/");
    int requestCount = 0;
    long reportStart = System.nanoTime();
    long reportPeriod = TimeUnit.SECONDS.toNanos(1);
    int reports = 0;
    double best = 0.0;
    // Run until we've printed enough reports.
    while (reports < NUM_REPORTS) {
        // Print a report if we haven't recently.
        long now = System.nanoTime();
        double reportDuration = now - reportStart;
        if (reportDuration > reportPeriod) {
            double requestsPerSecond = requestCount / reportDuration * TimeUnit.SECONDS.toNanos(1);
            if (VERBOSE) {
                System.out.println(String.format("Requests per second: %.1f", requestsPerSecond));
            }
            best = Math.max(best, requestsPerSecond);
            requestCount = 0;
            reportStart = now;
            reports++;
        }
        // Fill the job queue with work.
        while (httpClient.acceptingJobs()) {
            httpClient.enqueue(url);
            requestCount++;
        }
        // The job queue is full. Take a break.
        sleep(1);
    }
    return best;
}
Also used : MockWebServer(okhttp3.mockwebserver.MockWebServer) HttpUrl(okhttp3.HttpUrl) ArbitraryMeasurement(com.google.caliper.model.ArbitraryMeasurement)

Example 17 with MockWebServer

use of okhttp3.mockwebserver.MockWebServer in project okhttp by square.

the class DisconnectTest method setUp.

@Before
public void setUp() throws Exception {
    // Sockets on some platforms can have large buffers that mean writes do not block when
    // required. These socket factories explicitly set the buffer sizes on sockets created.
    server = new MockWebServer();
    server.setServerSocketFactory(new DelegatingServerSocketFactory(ServerSocketFactory.getDefault()) {

        @Override
        protected ServerSocket configureServerSocket(ServerSocket serverSocket) throws IOException {
            serverSocket.setReceiveBufferSize(SOCKET_BUFFER_SIZE);
            return serverSocket;
        }
    });
    client = defaultClient().newBuilder().socketFactory(new DelegatingSocketFactory(SocketFactory.getDefault()) {

        @Override
        protected Socket configureSocket(Socket socket) throws IOException {
            socket.setSendBufferSize(SOCKET_BUFFER_SIZE);
            socket.setReceiveBufferSize(SOCKET_BUFFER_SIZE);
            return socket;
        }
    }).build();
}
Also used : DelegatingSocketFactory(okhttp3.DelegatingSocketFactory) DelegatingServerSocketFactory(okhttp3.DelegatingServerSocketFactory) MockWebServer(okhttp3.mockwebserver.MockWebServer) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket) Before(org.junit.Before)

Example 18 with MockWebServer

use of okhttp3.mockwebserver.MockWebServer in project retrofit by square.

the class AnnotatedConverters method main.

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();
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) GsonBuilder(com.google.gson.GsonBuilder) GsonBuilder(com.google.gson.GsonBuilder) SimpleXmlConverterFactory(retrofit2.converter.simplexml.SimpleXmlConverterFactory) Retrofit(retrofit2.Retrofit) MoshiConverterFactory(retrofit2.converter.moshi.MoshiConverterFactory) MockWebServer(okhttp3.mockwebserver.MockWebServer) GsonConverterFactory(retrofit2.converter.gson.GsonConverterFactory)

Example 19 with MockWebServer

use of okhttp3.mockwebserver.MockWebServer in project retrofit by square.

the class ChunkingConverter method main.

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();
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) Retrofit(retrofit2.Retrofit) MockWebServer(okhttp3.mockwebserver.MockWebServer)

Example 20 with MockWebServer

use of okhttp3.mockwebserver.MockWebServer in project retrofit by square.

the class DeserializeErrorBody method main.

public static void main(String... args) throws IOException {
    // Create a local web server which response with a 404 and JSON body.
    MockWebServer server = new MockWebServer();
    server.start();
    server.enqueue(new MockResponse().setResponseCode(404).setBody("{\"message\":\"Unable to locate resource\"}"));
    // Create our Service instance with a Retrofit pointing at the local web server and Gson.
    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).addConverterFactory(GsonConverterFactory.create()).build();
    Service service = retrofit.create(Service.class);
    Response<User> response = service.getUser().execute();
    // Normally you would check response.isSuccess() here before doing the following, but we know
    // this call will always fail. You could also use response.code() to determine whether to
    // convert the error body and/or which type to use for conversion.
    // Look up a converter for the Error type on the Retrofit instance.
    Converter<ResponseBody, Error> errorConverter = retrofit.responseBodyConverter(Error.class, new Annotation[0]);
    // Convert the error body into our Error type.
    Error error = errorConverter.convert(response.errorBody());
    System.out.println("ERROR: " + error.message);
    server.shutdown();
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) Retrofit(retrofit2.Retrofit) MockWebServer(okhttp3.mockwebserver.MockWebServer) ResponseBody(okhttp3.ResponseBody)

Aggregations

MockWebServer (okhttp3.mockwebserver.MockWebServer)48 MockResponse (okhttp3.mockwebserver.MockResponse)31 Test (org.junit.Test)20 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)16 Before (org.junit.Before)14 IOException (java.io.IOException)9 CookieManager (java.net.CookieManager)7 HttpCookie (java.net.HttpCookie)5 Retrofit (retrofit2.Retrofit)5 ServerSocket (java.net.ServerSocket)4 Socket (java.net.Socket)4 Request (okhttp3.Request)4 OAuthRequest (com.github.scribejava.core.model.OAuthRequest)3 Response (com.github.scribejava.core.model.Response)3 InputStream (java.io.InputStream)3 InterruptedIOException (java.io.InterruptedIOException)3 HttpURLConnection (java.net.HttpURLConnection)3 URI (java.net.URI)3 URL (java.net.URL)3 List (java.util.List)3