Example usage for com.squareup.okhttp Response header

List of usage examples for com.squareup.okhttp Response header

Introduction

In this page you can find the example usage for com.squareup.okhttp Response header.

Prototype

public String header(String name) 

Source Link

Usage

From source file:abtlibrary.utils.as24ApiClient.ApiClient.java

License:Apache License

/**
 * Prepare file for download//  www. j a v  a  2s .c o m
 *
 * @param response An instance of the Response object
 * @throws IOException If fail to prepare file for download
 * @return Prepared file for the download
 */
public File prepareDownloadFile(Response response) throws IOException {
    String filename = null;
    String contentDisposition = response.header("Content-Disposition");
    if (contentDisposition != null && !"".equals(contentDisposition)) {
        // Get filename from the Content-Disposition header.
        Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?");
        Matcher matcher = pattern.matcher(contentDisposition);
        if (matcher.find()) {
            filename = sanitizeFilename(matcher.group(1));
        }
    }

    String prefix = null;
    String suffix = null;
    if (filename == null) {
        prefix = "download-";
        suffix = "";
    } else {
        int pos = filename.lastIndexOf(".");
        if (pos == -1) {
            prefix = filename + "-";
        } else {
            prefix = filename.substring(0, pos) + "-";
            suffix = filename.substring(pos);
        }
        // File.createTempFile requires the prefix to be at least three characters long
        if (prefix.length() < 3)
            prefix = "download-";
    }

    if (tempFolderPath == null)
        return File.createTempFile(prefix, suffix);
    else
        return File.createTempFile(prefix, suffix, new File(tempFolderPath));
}

From source file:at.bitfire.dav4android.DavResource.java

License:Open Source License

public void options() throws IOException, HttpException, DavException {
    capabilities.clear();/*  w  w  w. j  a  v a2s .  c  om*/

    Response response = httpClient.newCall(new Request.Builder().method("OPTIONS", null).url(location).build())
            .execute();
    checkStatus(response);

    String dav = response.header("DAV");
    if (dav != null)
        for (String capability : TextUtils.split(dav, ","))
            capabilities.add(capability.trim());
}

From source file:at.bitfire.dav4android.DavResource.java

License:Open Source License

/**
 * Sends a GET request to the resource. Note that this method expects the server to
 * return an ETag (which is required for CalDAV and CardDAV, but not for WebDAV in general).
 * @param accept    content of Accept header (must not be null, but may be &#42;&#47;* )
 * @return          response body//from w  ww.ja v a 2s  .  c om
 * @throws DavException    on WebDAV errors, or when the response doesn't contain an ETag
 */
public ResponseBody get(@NonNull String accept) throws IOException, HttpException, DavException {
    Response response = null;
    for (int attempt = 0; attempt < MAX_REDIRECTS; attempt++) {
        response = httpClient
                .newCall(new Request.Builder().get().url(location).header("Accept", accept).build()).execute();
        if (response.isRedirect())
            processRedirection(response);
        else
            break;
    }
    checkStatus(response);

    String eTag = response.header("ETag");
    if (TextUtils.isEmpty(eTag))
        // CalDAV servers MUST return ETag on GET [https://tools.ietf.org/html/rfc4791#section-5.3.4]
        // CardDAV servers MUST return ETag on GET [https://tools.ietf.org/html/rfc6352#section-6.3.2.3]
        throw new DavException("Received GET response without ETag");
    properties.put(GetETag.NAME, new GetETag(eTag));

    ResponseBody body = response.body();
    if (body == null)
        throw new HttpException("GET without response body");

    MediaType mimeType = body.contentType();
    if (mimeType != null)
        properties.put(GetContentType.NAME, new GetContentType(mimeType));

    return body;
}

From source file:at.bitfire.dav4android.DavResource.java

License:Open Source License

/**
 * Sends a PUT request to the resource.//from  w  ww .ja va 2 s. c om
 * @param body              new resource body to upload
 * @param ifMatchETag       value of "If-Match" header to set, or null to omit
 * @param ifNoneMatch       indicates whether "If-None-Match: *" ("don't overwrite anything existing") header shall be sent
 * @return                  true if the request was redirected successfully, i.e. #{@link #location} and maybe resource name may have changed
 */
public boolean put(@NonNull RequestBody body, String ifMatchETag, boolean ifNoneMatch)
        throws IOException, HttpException {
    boolean redirected = false;
    Response response = null;
    for (int attempt = 0; attempt < MAX_REDIRECTS; attempt++) {
        Request.Builder builder = new Request.Builder().put(body).url(location);

        if (ifMatchETag != null)
            // only overwrite specific version
            builder.header("If-Match", StringUtils.asQuotedString(ifMatchETag));
        if (ifNoneMatch)
            // don't overwrite anything existing
            builder.header("If-None-Match", "*");

        response = httpClient.newCall(builder.build()).execute();
        if (response.isRedirect()) {
            processRedirection(response);
            redirected = true;
        } else
            break;
    }
    checkStatus(response);

    String eTag = response.header("ETag");
    if (TextUtils.isEmpty(eTag))
        properties.remove(GetETag.NAME);
    else
        properties.put(GetETag.NAME, new GetETag(eTag));

    return redirected;
}

From source file:at.bitfire.dav4android.DavResource.java

License:Open Source License

void processRedirection(Response response) throws HttpException {
    HttpUrl target = null;/* ww w.  j  a v a 2 s . c o m*/

    String href = response.header("Location");
    if (href != null)
        target = location.resolve(href);

    if (target != null) {
        log.debug("Received redirection, new location=" + target);
        location = target;
    } else
        throw new HttpException("Received redirection without new location");
}

From source file:at.bitfire.dav4android.exception.ServiceUnavailableException.java

License:Open Source License

public ServiceUnavailableException(Response response) {
    super(response);

    // Retry-After  = "Retry-After" ":" ( HTTP-date | delta-seconds )
    // HTTP-date    = rfc1123-date | rfc850-date | asctime-date

    String strRetryAfter = response.header("Retry-After");
    if (strRetryAfter != null) {
        retryAfter = HttpDate.parse(strRetryAfter);

        if (retryAfter == null)
            // not a HTTP-date, must be delta-seconds
            try {
                int seconds = Integer.parseInt(strRetryAfter);

                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.SECOND, seconds);
                retryAfter = cal.getTime();

            } catch (NumberFormatException e) {
                Constants.log.warn("Received Retry-After which was not a HTTP-date nor delta-seconds");
            }//from  w  w w  .j  a  v  a 2 s. co  m
    }
}

From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java

License:Open Source License

@Test
public void networkInterceptorsObserveNetworkHeaders() throws Exception {
    server.enqueue(new MockResponse().setBody(gzip("abcabcabc")).addHeader("Content-Encoding: gzip"));

    client.networkInterceptors().add(new Interceptor() {
        @Override/* w  w  w  .  j  a  v a2s . co m*/
        public Response intercept(Chain chain) throws IOException {
            // The network request has everything: User-Agent, Host, Accept-Encoding.
            Request networkRequest = chain.request();
            assertNotNull(networkRequest.header("User-Agent"));
            assertEquals(server.get().getHostName() + ":" + server.get().getPort(),
                    networkRequest.header("Host"));
            assertNotNull(networkRequest.header("Accept-Encoding"));

            // The network response also has everything, including the raw gzipped content.
            Response networkResponse = chain.proceed(networkRequest);
            assertEquals("gzip", networkResponse.header("Content-Encoding"));
            return networkResponse;
        }
    });

    Request request = new Request.Builder().url(server.getUrl("/")).build();

    // No extra headers in the application's request.
    assertNull(request.header("User-Agent"));
    assertNull(request.header("Host"));
    assertNull(request.header("Accept-Encoding"));

    // No extra headers in the application's response.
    Response response = FiberOkHttpUtil.executeInFiber(client, request);
    assertNull(request.header("Content-Encoding"));
    assertEquals("abcabcabc", response.body().string());
}

From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java

License:Open Source License

private void rewriteResponseFromServer(List<Interceptor> interceptors) throws Exception {
    server.enqueue(new MockResponse().addHeader("Original-Header: foo").setBody("abc"));

    interceptors.add(new Interceptor() {
        @Override//from  w  w w.ja  v  a 2 s  .  c o m
        public Response intercept(Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());
            return originalResponse.newBuilder().body(uppercase(originalResponse.body()))
                    .addHeader("OkHttp-Intercepted", "yep").build();
        }
    });

    Request request = new Request.Builder().url(server.getUrl("/")).build();

    Response response = FiberOkHttpUtil.executeInFiber(client, request);
    assertEquals("ABC", response.body().string());
    assertEquals("yep", response.header("OkHttp-Intercepted"));
    assertEquals("foo", response.header("Original-Header"));
}

From source file:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java

License:Apache License

@Test
public void networkInterceptorsObserveNetworkHeaders() throws Exception {
    server.enqueue(new MockResponse().setBody(gzip("abcabcabc")).addHeader("Content-Encoding: gzip"));

    client.networkInterceptors().add(new Interceptor() {
        @Override/*  w  ww . j  a  va  2  s  .  c om*/
        public Response intercept(Chain chain) throws IOException {
            // The network request has everything: User-Agent, Host, Accept-Encoding.
            Request networkRequest = chain.request();
            assertNotNull(networkRequest.header("User-Agent"));
            assertEquals(server.getHostName() + ":" + server.getPort(), networkRequest.header("Host"));
            assertNotNull(networkRequest.header("Accept-Encoding"));

            // The network response also has everything, including the raw gzipped content.
            Response networkResponse = chain.proceed(networkRequest);
            assertEquals("gzip", networkResponse.header("Content-Encoding"));
            return networkResponse;
        }
    });

    Request request = new Request.Builder().url(server.url("/")).build();

    // No extra headers in the application's request.
    assertNull(request.header("User-Agent"));
    assertNull(request.header("Host"));
    assertNull(request.header("Accept-Encoding"));

    // No extra headers in the application's response.
    Response response = client.newCall(request).execute();
    assertNull(request.header("Content-Encoding"));
    assertEquals("abcabcabc", response.body().string());
}

From source file:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java

License:Apache License

private void rewriteResponseFromServer(List<Interceptor> interceptors) throws Exception {
    server.enqueue(new MockResponse().addHeader("Original-Header: foo").setBody("abc"));

    interceptors.add(new Interceptor() {
        @Override/*from   w  w w.jav  a 2  s.c  om*/
        public Response intercept(Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());
            return originalResponse.newBuilder().body(uppercase(originalResponse.body()))
                    .addHeader("OkHttp-Intercepted", "yep").build();
        }
    });

    Request request = new Request.Builder().url(server.url("/")).build();

    Response response = client.newCall(request).execute();
    assertEquals("ABC", response.body().string());
    assertEquals("yep", response.header("OkHttp-Intercepted"));
    assertEquals("foo", response.header("Original-Header"));
}