Search in sources :

Example 61 with Headers

use of okhttp3.Headers in project okhttp by square.

the class UrlConnectionCacheTest method emptyResponseHeaderNameFromCacheIsLenient.

@Test
public void emptyResponseHeaderNameFromCacheIsLenient() throws Exception {
    Headers.Builder headers = new Headers.Builder().add("Cache-Control: max-age=120");
    Internal.instance.addLenient(headers, ": A");
    server.enqueue(new MockResponse().setHeaders(headers.build()).setBody("body"));
    HttpURLConnection connection = urlFactory.open(server.url("/").url());
    assertEquals("A", connection.getHeaderField(""));
    assertEquals("body", readAscii(connection));
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) HttpURLConnection(java.net.HttpURLConnection) Test(org.junit.Test)

Example 62 with Headers

use of okhttp3.Headers in project glide by bumptech.

the class HttpUrlFetcherServerTest method testAppliesHeadersInGlideUrl.

@Test
public void testAppliesHeadersInGlideUrl() throws Exception {
    mockWebServer.enqueue(new MockResponse().setResponseCode(200));
    String headerField = "field";
    String headerValue = "value";
    Map<String, String> headersMap = new HashMap<>();
    headersMap.put(headerField, headerValue);
    Headers headers = mock(Headers.class);
    when(headers.getHeaders()).thenReturn(headersMap);
    getFetcher(headers).loadData(Priority.HIGH, callback);
    assertThat(mockWebServer.takeRequest().getHeader(headerField)).isEqualTo(headerValue);
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) HashMap(java.util.HashMap) Headers(com.bumptech.glide.load.model.Headers) Test(org.junit.Test)

Example 63 with Headers

use of okhttp3.Headers in project Fast-Android-Networking by amitshekhariitbhu.

the class HttpLoggingInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Level level = this.level;
    Request request = chain.request();
    if (level == Level.NONE) {
        return chain.proceed(request);
    }
    boolean logBody = level == Level.BODY;
    boolean logHeaders = logBody || level == Level.HEADERS;
    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;
    Connection connection = chain.connection();
    Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
    String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol;
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    logger.log(requestStartMessage);
    if (logHeaders) {
        if (hasRequestBody) {
            // them to be included (when available) so there values are known.
            if (requestBody.contentType() != null) {
                logger.log("Content-Type: " + requestBody.contentType());
            }
            if (requestBody.contentLength() != -1) {
                logger.log("Content-Length: " + requestBody.contentLength());
            }
        }
        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            String name = headers.name(i);
            // Skip headers from the request body as they are explicitly logged above.
            if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                logger.log(name + ": " + headers.value(i));
            }
        }
        if (!logBody || !hasRequestBody) {
            logger.log("--> END " + request.method());
        } else if (bodyEncoded(request.headers())) {
            logger.log("--> END " + request.method() + " (encoded body omitted)");
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            logger.log("");
            if (isPlaintext(buffer)) {
                logger.log(buffer.readString(charset));
                logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
            } else {
                logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength() + "-byte body omitted)");
            }
        }
    }
    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        logger.log("<-- HTTP FAILED: " + e);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
    logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')');
    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            logger.log(headers.name(i) + ": " + headers.value(i));
        }
        if (!logBody || !HttpHeaders.hasBody(response)) {
            logger.log("<-- END HTTP");
        } else if (bodyEncoded(response.headers())) {
            logger.log("<-- END HTTP (encoded body omitted)");
        } else {
            BufferedSource source = responseBody.source();
            // Buffer the entire body.
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();
            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            if (!isPlaintext(buffer)) {
                logger.log("");
                logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
                return response;
            }
            if (contentLength != 0) {
                logger.log("");
                logger.log(buffer.clone().readString(charset));
            }
            logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
        }
    }
    return response;
}
Also used : Buffer(okio.Buffer) HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) Request(okhttp3.Request) Connection(okhttp3.Connection) Charset(java.nio.charset.Charset) IOException(java.io.IOException) EOFException(java.io.EOFException) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) MediaType(okhttp3.MediaType) Protocol(okhttp3.Protocol) RequestBody(okhttp3.RequestBody) BufferedSource(okio.BufferedSource)

Example 64 with Headers

use of okhttp3.Headers in project Fast-Android-Networking by amitshekhariitbhu.

the class ApiTestActivity method checkSynchronousCall.

public void checkSynchronousCall(View view) {
    new Thread(new Runnable() {

        @Override
        public void run() {
            String url = "http://www.colorado.edu/conflict/peace/download/peace_problem.ZIP";
            ANRequest requestOne = AndroidNetworking.download(url, Utils.getRootDirPath(getApplicationContext()), "file1.zip").build().setAnalyticsListener(new AnalyticsListener() {

                @Override
                public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) {
                    Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis);
                    Log.d(TAG, " bytesSent : " + bytesSent);
                    Log.d(TAG, " bytesReceived : " + bytesReceived);
                    Log.d(TAG, " isFromCache : " + isFromCache);
                }
            }).setDownloadProgressListener(new DownloadProgressListener() {

                @Override
                public void onProgress(long bytesDownloaded, long totalBytes) {
                    Log.d(TAG, "bytesDownloaded : " + bytesDownloaded + " totalBytes : " + totalBytes);
                    Log.d(TAG, "setDownloadProgressListener isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
                }
            });
            ANResponse<String> responseOne = requestOne.executeForDownload();
            if (responseOne.isSuccess()) {
                Log.d(TAG, "checkSynchronousCall : download success");
                Log.d(TAG, "checkSynchronousCall : download result " + responseOne.getResult());
                Response response = responseOne.getOkHttpResponse();
                Log.d(TAG, "checkSynchronousCall : headers : " + response.headers().toString());
            } else {
                Log.d(TAG, "checkSynchronousCall : download failed");
                Utils.logError(TAG, responseOne.getError());
            }
            ANRequest requestTwo = AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY).addPathParameter("pageNumber", "0").addQueryParameter("limit", "3").build().setAnalyticsListener(new AnalyticsListener() {

                @Override
                public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) {
                    Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis);
                    Log.d(TAG, " bytesSent : " + bytesSent);
                    Log.d(TAG, " bytesReceived : " + bytesReceived);
                    Log.d(TAG, " isFromCache : " + isFromCache);
                }
            });
            ANResponse<List<User>> responseTwo = requestTwo.executeForObjectList(User.class);
            if (responseTwo.isSuccess()) {
                Log.d(TAG, "checkSynchronousCall : response success");
                List<User> users = responseTwo.getResult();
                Log.d(TAG, "userList size : " + users.size());
                for (User user : users) {
                    Log.d(TAG, "id : " + user.id);
                    Log.d(TAG, "firstname : " + user.firstname);
                    Log.d(TAG, "lastname : " + user.lastname);
                }
                Response response = responseTwo.getOkHttpResponse();
                Log.d(TAG, "checkSynchronousCall : headers : " + response.headers().toString());
            } else {
                Log.d(TAG, "checkSynchronousCall : response failed");
                Utils.logError(TAG, responseTwo.getError());
            }
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("firstname", "Rohit");
                jsonObject.put("lastname", "Kumar");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            ANRequest requestThree = AndroidNetworking.post(ApiEndPoint.BASE_URL + ApiEndPoint.POST_CREATE_AN_USER).addJSONObjectBody(jsonObject).build().setAnalyticsListener(new AnalyticsListener() {

                @Override
                public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) {
                    Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis);
                    Log.d(TAG, " bytesSent : " + bytesSent);
                    Log.d(TAG, " bytesReceived : " + bytesReceived);
                    Log.d(TAG, " isFromCache : " + isFromCache);
                }
            });
            ANResponse<JSONObject> responseThree = requestThree.executeForJSONObject();
            if (responseThree.isSuccess()) {
                Log.d(TAG, "checkSynchronousCall : jsonObjectANResponse success");
                JSONObject jsonObjectFinal = responseThree.getResult();
                Log.d(TAG, "checkSynchronousCall : jsonObjectANResponse result " + jsonObjectFinal.toString());
                Response response = responseThree.getOkHttpResponse();
                Log.d(TAG, "checkSynchronousCall : headers : " + response.headers().toString());
            } else {
                Log.d(TAG, "checkSynchronousCall : jsonObjectANResponse failed");
                Utils.logError(TAG, responseThree.getError());
            }
            ANRequest requestFour = AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY).addPathParameter("pageNumber", "0").addQueryParameter("limit", "3").build().setAnalyticsListener(new AnalyticsListener() {

                @Override
                public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) {
                    Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis);
                    Log.d(TAG, " bytesSent : " + bytesSent);
                    Log.d(TAG, " bytesReceived : " + bytesReceived);
                    Log.d(TAG, " isFromCache : " + isFromCache);
                }
            });
            ANResponse<Response> responseFour = requestFour.executeForOkHttpResponse();
            if (responseFour.isSuccess()) {
                Log.d(TAG, "checkSynchronousCall : okHttpResponse success");
                Response okHttpResponse = responseFour.getResult();
                if (okHttpResponse != null) {
                    if (okHttpResponse.isSuccessful()) {
                        Log.d(TAG, "response is successful");
                        try {
                            Log.d(TAG, "response : " + okHttpResponse.body().source().readUtf8());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Log.d(TAG, "response is not successful");
                    }
                } else {
                    Log.d(TAG, "response is null");
                }
            } else {
                Log.d(TAG, "checkSynchronousCall : okHttpResponse failed");
                Utils.logError(TAG, responseFour.getError());
            }
        }
    }).start();
}
Also used : ANRequest(com.androidnetworking.common.ANRequest) AnalyticsListener(com.androidnetworking.interfaces.AnalyticsListener) User(com.networking.model.User) DownloadProgressListener(com.androidnetworking.interfaces.DownloadProgressListener) JSONException(org.json.JSONException) IOException(java.io.IOException) Response(okhttp3.Response) ANResponse(com.androidnetworking.common.ANResponse) JSONObject(org.json.JSONObject) List(java.util.List)

Example 65 with Headers

use of okhttp3.Headers in project buck by facebook.

the class ArtifactCaches method createHttpArtifactCache.

private static ArtifactCache createHttpArtifactCache(HttpCacheEntry cacheDescription, final String hostToReportToRemote, final BuckEventBus buckEventBus, ProjectFilesystem projectFilesystem, ListeningExecutorService httpWriteExecutorService, ArtifactCacheBuckConfig config, NetworkCacheFactory factory, boolean distributedBuildModeEnabled) {
    // Setup the default client to use.
    OkHttpClient.Builder storeClientBuilder = new OkHttpClient.Builder();
    storeClientBuilder.networkInterceptors().add(chain -> chain.proceed(chain.request().newBuilder().addHeader("X-BuckCache-User", stripNonAscii(System.getProperty("user.name", "<unknown>"))).addHeader("X-BuckCache-Host", stripNonAscii(hostToReportToRemote)).build()));
    int timeoutSeconds = cacheDescription.getTimeoutSeconds();
    setTimeouts(storeClientBuilder, timeoutSeconds);
    storeClientBuilder.connectionPool(new ConnectionPool(/* maxIdleConnections */
    (int) config.getThreadPoolSize(), /* keepAliveDurationMs */
    config.getThreadPoolKeepAliveDurationMillis(), TimeUnit.MILLISECONDS));
    // The artifact cache effectively only connects to a single host at a time. We should allow as
    // many concurrent connections to that host as we allow threads.
    Dispatcher dispatcher = new Dispatcher();
    dispatcher.setMaxRequestsPerHost((int) config.getThreadPoolSize());
    storeClientBuilder.dispatcher(dispatcher);
    final ImmutableMap<String, String> readHeaders = cacheDescription.getReadHeaders();
    final ImmutableMap<String, String> writeHeaders = cacheDescription.getWriteHeaders();
    // If write headers are specified, add them to every default client request.
    if (!writeHeaders.isEmpty()) {
        storeClientBuilder.networkInterceptors().add(chain -> chain.proceed(addHeadersToBuilder(chain.request().newBuilder(), writeHeaders).build()));
    }
    OkHttpClient storeClient = storeClientBuilder.build();
    // For fetches, use a client with a read timeout.
    OkHttpClient.Builder fetchClientBuilder = storeClient.newBuilder();
    setTimeouts(fetchClientBuilder, timeoutSeconds);
    // If read headers are specified, add them to every read client request.
    if (!readHeaders.isEmpty()) {
        fetchClientBuilder.networkInterceptors().add(chain -> chain.proceed(addHeadersToBuilder(chain.request().newBuilder(), readHeaders).build()));
    }
    fetchClientBuilder.networkInterceptors().add((chain -> {
        Response originalResponse = chain.proceed(chain.request());
        return originalResponse.newBuilder().body(new ProgressResponseBody(originalResponse.body(), buckEventBus)).build();
    }));
    OkHttpClient fetchClient = fetchClientBuilder.build();
    HttpService fetchService;
    HttpService storeService;
    switch(config.getLoadBalancingType()) {
        case CLIENT_SLB:
            HttpLoadBalancer clientSideSlb = config.getSlbConfig().createClientSideSlb(new DefaultClock(), buckEventBus, new CommandThreadFactory("ArtifactCaches.HttpLoadBalancer", SLB_THREAD_PRIORITY));
            fetchService = new RetryingHttpService(buckEventBus, new LoadBalancedService(clientSideSlb, fetchClient, buckEventBus), config.getMaxFetchRetries());
            storeService = new LoadBalancedService(clientSideSlb, storeClient, buckEventBus);
            break;
        case SINGLE_SERVER:
            URI url = cacheDescription.getUrl();
            fetchService = new SingleUriService(url, fetchClient);
            storeService = new SingleUriService(url, storeClient);
            break;
        default:
            throw new IllegalArgumentException("Unknown HttpLoadBalancer type: " + config.getLoadBalancingType());
    }
    String cacheName = cacheDescription.getName().map(input -> "http-" + input).orElse("http");
    boolean doStore = cacheDescription.getCacheReadMode().isDoStore();
    return factory.newInstance(NetworkCacheArgs.builder().setThriftEndpointPath(config.getHybridThriftEndpoint()).setCacheName(cacheName).setRepository(config.getRepository()).setScheduleType(config.getScheduleType()).setFetchClient(fetchService).setStoreClient(storeService).setDoStore(doStore).setProjectFilesystem(projectFilesystem).setBuckEventBus(buckEventBus).setHttpWriteExecutorService(httpWriteExecutorService).setErrorTextTemplate(cacheDescription.getErrorMessageFormat()).setDistributedBuildModeEnabled(distributedBuildModeEnabled).build());
}
Also used : ConnectionPool(okhttp3.ConnectionPool) BuckEventBus(com.facebook.buck.event.BuckEventBus) Okio(okio.Okio) Source(okio.Source) BytesReceivedEvent(com.facebook.buck.event.NetworkEvent.BytesReceivedEvent) RetryingHttpService(com.facebook.buck.slb.RetryingHttpService) Dispatcher(okhttp3.Dispatcher) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem) CommonGroups(com.facebook.buck.randomizedtrial.CommonGroups) BuckConfig(com.facebook.buck.cli.BuckConfig) ImmutableList(com.google.common.collect.ImmutableList) DefaultClock(com.facebook.buck.timing.DefaultClock) Map(java.util.Map) ForwardingSource(okio.ForwardingSource) Response(okhttp3.Response) HttpLoadBalancer(com.facebook.buck.slb.HttpLoadBalancer) URI(java.net.URI) LoadBalancedService(com.facebook.buck.slb.LoadBalancedService) Path(java.nio.file.Path) MediaType(okhttp3.MediaType) ResponseBody(okhttp3.ResponseBody) HttpService(com.facebook.buck.slb.HttpService) Logger(com.facebook.buck.log.Logger) Request(okhttp3.Request) Buffer(okio.Buffer) SingleUriService(com.facebook.buck.slb.SingleUriService) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) CharMatcher(com.google.common.base.CharMatcher) IOException(java.io.IOException) HumanReadableException(com.facebook.buck.util.HumanReadableException) CommandThreadFactory(com.facebook.buck.log.CommandThreadFactory) TimeUnit(java.util.concurrent.TimeUnit) BufferedSource(okio.BufferedSource) OkHttpClient(okhttp3.OkHttpClient) Optional(java.util.Optional) ConnectionPool(okhttp3.ConnectionPool) AsyncCloseable(com.facebook.buck.util.AsyncCloseable) RandomizedTrial(com.facebook.buck.randomizedtrial.RandomizedTrial) DirCacheExperimentEvent(com.facebook.buck.event.DirCacheExperimentEvent) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) OkHttpClient(okhttp3.OkHttpClient) CommandThreadFactory(com.facebook.buck.log.CommandThreadFactory) Dispatcher(okhttp3.Dispatcher) RetryingHttpService(com.facebook.buck.slb.RetryingHttpService) URI(java.net.URI) Response(okhttp3.Response) RetryingHttpService(com.facebook.buck.slb.RetryingHttpService) HttpService(com.facebook.buck.slb.HttpService) DefaultClock(com.facebook.buck.timing.DefaultClock) LoadBalancedService(com.facebook.buck.slb.LoadBalancedService) SingleUriService(com.facebook.buck.slb.SingleUriService) HttpLoadBalancer(com.facebook.buck.slb.HttpLoadBalancer)

Aggregations

Test (org.junit.Test)69 Request (okhttp3.Request)58 Response (okhttp3.Response)53 Headers (okhttp3.Headers)46 IOException (java.io.IOException)34 MockResponse (okhttp3.mockwebserver.MockResponse)33 HttpHeaders (okhttp3.internal.http.HttpHeaders)29 ResponseBody (okhttp3.ResponseBody)27 RequestBody (okhttp3.RequestBody)21 List (java.util.List)19 MediaType (okhttp3.MediaType)16 HashMap (java.util.HashMap)15 Map (java.util.Map)15 ANResponse (com.androidnetworking.common.ANResponse)13 AnalyticsListener (com.androidnetworking.interfaces.AnalyticsListener)13 LinkedHashMap (java.util.LinkedHashMap)13 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)13 Buffer (okio.Buffer)12 ANError (com.androidnetworking.error.ANError)11 HttpURLConnection (java.net.HttpURLConnection)11