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:io.github.hidroh.materialistic.accounts.UserServicesClient.java

License:Apache License

@WorkerThread
private void doSubmit(String title, String content, String fnid, boolean isUrl, final Callback callback) {
    if (TextUtils.isEmpty(fnid)) {
        postError(callback);//from w  w w  . jav a  2s  .c o m
        return;
    }
    mClient.newCall(new Request.Builder()
            .url(HttpUrl.parse(BASE_WEB_URL).newBuilder().addPathSegment(SUBMIT_POST_PATH).build())
            .post(new FormEncodingBuilder().add(SUBMIT_PARAM_FNID, fnid).add(SUBMIT_PARAM_FNOP, DEFAULT_FNOP)
                    .add(SUBMIT_PARAM_TITLE, title).add(isUrl ? SUBMIT_PARAM_URL : SUBMIT_PARAM_TEXT, content)
                    .build())
            .build()).enqueue(new com.squareup.okhttp.Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    postError(callback);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    boolean redirect = response.code() == HttpURLConnection.HTTP_MOVED_TEMP;
                    if (!redirect) {
                        postError(callback);
                        return;
                    }
                    String location = response.header(HEADER_LOCATION);
                    switch (location) {
                    case DEFAULT_SUBMIT_REDIRECT:
                        postResult(callback, true);
                        break;
                    default:
                        postError(callback);
                        break;
                    }
                }
            });
}

From source file:io.macgyver.plugin.elb.a10.A10ClientImpl.java

License:Apache License

protected ObjectNode parseJsonResponse(Response response, String method) {
    try {//  w  w  w  .  j  a  v  a  2  s .  c  om
        Preconditions.checkNotNull(response);

        String contentType = response.header("Content-type");

        // aXAPI is very sketchy with regard to content type of response.
        // Sometimes we get XML/HTML back even though
        // we ask for JSON. This hack helps figure out what is going on.

        String val = response.body().string().trim();
        if (!val.startsWith("{") && !val.startsWith("[")) {
            throw new ElbException("response contained non-JSON data: " + val);
        }

        ObjectNode json = (ObjectNode) mapper.readTree(val);

        if (logger.isDebugEnabled()) {

            String body = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
            logger.debug("response: \n{}", body);
        }
        throwExceptionIfNecessary(json);
        return json;
    } catch (IOException e) {
        throw new ElbException(e);
    }
}

From source file:io.macgyver.test.MockWebServerTest.java

License:Apache License

@Test
public void testIt() throws IOException, InterruptedException {

    // set up mock response
    mockServer.enqueue(//from   w w w.j a va  2 s.c o  m
            new MockResponse().setBody("{\"name\":\"Rob\"}").addHeader("Content-type", "application/json"));

    // set up client and request
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(mockServer.getUrl("/test").toString())
            .post(RequestBody.create(MediaType.parse("application/json"), "{}"))
            .header("Authorization", Credentials.basic("scott", "tiger")).build();

    // make the call
    Response response = client.newCall(request).execute();

    // check the response
    assertThat(response.code()).isEqualTo(200);
    assertThat(response.header("content-type")).isEqualTo("application/json");

    // check the response body
    JsonNode n = new ObjectMapper().readTree(response.body().string());
    assertThat(n.path("name").asText()).isEqualTo("Rob");

    // now make sure that the request was as we exepected it to be
    RecordedRequest recordedRequest = mockServer.takeRequest();
    assertThat(recordedRequest.getPath()).isEqualTo("/test");
    assertThat(recordedRequest.getHeader("Authorization")).isEqualTo("Basic c2NvdHQ6dGlnZXI=");

}

From source file:keywhiz.service.filters.SecurityHeadersFilterTest.java

License:Apache License

@Test
public void checkSecurityHeaders() throws Exception {
    Request request = new Request.Builder().url(testUrl("/ui/")).get().build();

    Response response = client.newCall(request).execute();

    assertThat(response.header("X-Content-Security-Policy")).isEqualTo("default-src 'self'");
    assertThat(response.header("X-XSS-Protection")).isEqualTo("0");
    assertThat(response.header("X-Content-Type-Options")).isEqualTo("nosniff");
    assertThat(response.header("X-Frame-Options")).isEqualTo("DENY");
    assertThat(response.header("Strict-Transport-Security")).isEqualTo("max-age=31536000; includeSubDomains");
}

From source file:keywhiz.UiAssetsBundleTest.java

License:Apache License

@Test
public void rootRedirects() throws Exception {
    Request request = new Request.Builder().url(testUrl("/")).get().build();

    Response response = client.newCall(request).execute();
    assertThat(response.code()).isEqualTo(302);
    String locationHeader = response.header(HttpHeaders.LOCATION);
    assertThat(locationHeader).endsWith("/ui/");
}

From source file:keywhiz.UiAssetsBundleTest.java

License:Apache License

@Test
public void incompleteUiRedirects() throws Exception {
    Request request = new Request.Builder().url(testUrl("/ui")).get().build();

    Response response = client.newCall(request).execute();
    assertThat(response.code()).isEqualTo(302);
    String locationHeader = response.header(HttpHeaders.LOCATION);
    assertThat(locationHeader).endsWith("/ui/");
}

From source file:net.uiqui.oblivion.client.rest.RestOutput.java

License:Apache License

public static RestOutput parse(Response response) throws IOException {
    final int status = response.code();

    final String etagHeader = response.header("ETag");

    Long etag = null;/*from w  w w. j a  va  2 s .  c  o m*/

    if (etagHeader != null) {
        etag = Long.valueOf(etagHeader);
    }

    final String json = response.body().string();

    return new RestOutput(status, etag, json);
}

From source file:org.dataconservancy.cos.packaging.cli.PackageGenerationApp.java

License:Apache License

/**
 * @param args/*  w  ww.j  av a2  s  .  c  o  m*/
 */
public static void main(final String[] args) {

    final PackageGenerationApp application = new PackageGenerationApp();

    final CmdLineParser parser = new CmdLineParser(application);
    parser.setUsageWidth(80);

    try {
        parser.parseArgument(args);

        /* Handle general options such as help, version */
        if (application.help) {
            parser.printUsage(System.err);
            System.err.println();
            System.exit(0);
        } else if (application.version) {
            System.err.println(PackageGenerationApp.class.getPackage().getImplementationVersion());
            System.exit(0);
        }

        final Properties props = System.getProperties();

        if (confFile.exists() && confFile.isFile()) {
            props.setProperty("osf.client.conf", confFile.toURI().toString());
        } else {
            System.err.println("Supplied OSF Client Configuration File " + confFile.getCanonicalPath()
                    + " does not exist or is not a file.");
            System.exit(1);
        }

        CTX = new ClassPathXmlApplicationContext(
                "classpath*:org/dataconservancy/cos/osf/client/config/applicationContext.xml",
                "classpath*:org/dataconservancy/cos/osf/client/retrofit/applicationContext.xml",
                "classpath:/org/dataconservancy/cos/packaging/config/applicationContext.xml");

        final Response response = CTX.getBean("okHttpClient", OkHttpClient.class)
                .newCall(new Request.Builder().head().url(registrationUrl).build()).execute();

        if (response.code() != 200) {
            System.err.println("There was an error executing '" + registrationUrl + "', response code "
                    + response.code() + " reason: '" + response.message() + "'");
            System.err.print("Please be sure you are using a valid API URL to a node or registration, ");
            System.err.println("and have properly configured authorization credentials, if necessary.");
            System.exit(1);
        }

        if (!response.header("Content-Type").contains("json")) {
            System.err.println("Provided URL '" + registrationUrl + "' does not return JSON (Content-Type was '"
                    + response.header("Content-Type") + "')");
            System.err.println("Please be sure you are using a valid API URL to a node or registration.");
            System.exit(1);
        }

        final String guid = parseGuid(registrationUrl);

        if (packageName == null) {
            packageName = guid;
        } else if (!(packageName.length() > 0)) {
            System.err.println("Bag name must have positive length.");
            System.exit(1);
        }

        if (outputLocation == null) {
            outputLocation = new File(packageName);
        }

        if (outputLocation.exists()) {
            System.err
                    .println("Destination directory " + outputLocation.getCanonicalPath() + " already exists!  "
                            + "Either (re)move the directory, or choose a different output location.");
            System.exit(1);
        }

        FileUtils.forceMkdir(outputLocation);

        if (bagMetadataFile != null && (!bagMetadataFile.exists() || !bagMetadataFile.isFile())) {
            System.err.println("Supplied bag metadata file " + bagMetadataFile.getCanonicalPath()
                    + " does not exist or is not a file.");
            System.exit(1);
        }

        /* Run the package generation application proper */
        application.run();

    } catch (CmdLineException e) {
        /*
         * This is an error in command line args, just print out usage data
         * and description of the error.
         */
        System.err.println(e.getMessage());
        parser.printUsage(System.err);
        System.err.println();
        System.exit(1);
    } catch (Exception e) {
        if (e.getMessage() == null || e.getMessage().equals("null")) {
            System.err.println("There was an unrecoverable error:");
            e.printStackTrace(System.err);
        } else {
            System.err.println("There was an unrecoverable error: " + e.getMessage());
            e.printStackTrace(System.err);
        }

        System.exit(1);
    }
}

From source file:org.mariotaku.twidere.util.OAuthPasswordAuthenticator.java

License:Open Source License

public OAuthPasswordAuthenticator(final TwitterOAuth oauth,
        final LoginVerificationCallback loginVerificationCallback, final String userAgent) {
    final RestClient restClient = RestAPIFactory.getRestClient(oauth);
    this.oauth = oauth;
    this.client = (OkHttpRestClient) restClient.getRestClient();
    final OkHttpClient okhttp = client.getClient();
    okhttp.setCookieHandler(new CookieManager());
    okhttp.networkInterceptors().add(new Interceptor() {
        @Override//  w w w.  ja  v  a  2 s  . c o  m
        public Response intercept(Chain chain) throws IOException {
            final Response response = chain.proceed(chain.request());
            if (!response.isRedirect()) {
                return response;
            }
            final String location = response.header("Location");
            final Response.Builder builder = response.newBuilder();
            if (!TextUtils.isEmpty(location) && !endpoint.checkEndpoint(location)) {
                final HttpUrl originalLocation = HttpUrl
                        .get(URI.create("https://api.twitter.com/").resolve(location));
                final HttpUrl.Builder locationBuilder = HttpUrl.parse(endpoint.getUrl()).newBuilder();
                for (String pathSegments : originalLocation.pathSegments()) {
                    locationBuilder.addPathSegment(pathSegments);
                }
                for (int i = 0, j = originalLocation.querySize(); i < j; i++) {
                    final String name = originalLocation.queryParameterName(i);
                    final String value = originalLocation.queryParameterValue(i);
                    locationBuilder.addQueryParameter(name, value);
                }
                final String encodedFragment = originalLocation.encodedFragment();
                if (encodedFragment != null) {
                    locationBuilder.encodedFragment(encodedFragment);
                }
                final HttpUrl newLocation = locationBuilder.build();
                builder.header("Location", newLocation.toString());
            }
            return builder.build();
        }
    });
    this.endpoint = restClient.getEndpoint();
    this.loginVerificationCallback = loginVerificationCallback;
    this.userAgent = userAgent;
}

From source file:org.mythtv.services.api.ServerVersionQuery.java

License:Apache License

private static ApiVersion getMythVersion(String baseUri, OkHttpClient client) throws IOException {
    StringBuilder urlBuilder = new StringBuilder(baseUri);
    if (!baseUri.endsWith("/"))
        urlBuilder.append("/");
    urlBuilder.append("Myth/GetHostName");
    Request request = new Request.Builder().url(urlBuilder.toString())
            .addHeader("User-Agent", "MythTv Service API").addHeader("Connection", "Close").build();
    Response response = client.newCall(request).execute();
    if (response.isSuccessful()) {
        String serverHeader = response.header(MYTHTV_SERVER_HEADER);
        if (!Strings.isNullOrEmpty(serverHeader)) {
            // we have our header get the version.
            int idx = serverHeader.indexOf(MYTHTV_SERVER_MYTHVERSION);
            if (idx >= 0) {
                idx += MYTHTV_SERVER_MYTHVERSION.length();
                String version = serverHeader.substring(idx);
                if (version.contains("0.27"))
                    return ApiVersion.v027;
                if (version.contains("0.28"))
                    return ApiVersion.v028;
            }//from  w w w .j  a va 2  s.com
        }
    }
    return ApiVersion.NotSupported;
}