Example usage for com.squareup.okhttp Response code

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

Introduction

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

Prototype

int code

To view the source code for com.squareup.okhttp Response code.

Click Source Link

Usage

From source file:com.battlelancer.seriesguide.thetvdbapi.TheTVDB.java

License:Apache License

/**
 * Downloads the XML or ZIP file from the given URL, passing a valid response to {@link
 * Xml#parse(InputStream, android.util.Xml.Encoding, ContentHandler)} using the given {@link
 * ContentHandler}.// w  w  w.  ja  va  2  s .c o m
 */
private static void downloadAndParse(Context context, ContentHandler handler, String urlString,
        boolean isZipFile) throws TvdbException {
    Request request = new Request.Builder().url(urlString).build();

    Response response;
    try {
        response = ServiceUtils.getCachingOkHttpClient(context).newCall(request).execute();
    } catch (IOException e) {
        throw new TvdbException(e.getMessage() + " " + urlString, e);
    }

    int statusCode = response.code();
    if (statusCode == 404) {
        // special case: item does not exist (any longer)
        throw new TvdbException(response.code() + " " + response.message() + " " + urlString, true, null);
    }
    if (!response.isSuccessful()) {
        // other non-2xx response
        throw new TvdbException(response.code() + " " + response.message() + " " + urlString);
    }

    try {
        final InputStream input = response.body().byteStream();
        if (isZipFile) {
            // We downloaded the compressed file from TheTVDB
            final ZipInputStream zipin = new ZipInputStream(input);
            zipin.getNextEntry();
            try {
                Xml.parse(zipin, Xml.Encoding.UTF_8, handler);
            } finally {
                zipin.close();
            }
        } else {
            try {
                Xml.parse(input, Xml.Encoding.UTF_8, handler);
            } finally {
                if (input != null) {
                    input.close();
                }
            }
        }
    } catch (SAXException | IOException | AssertionError e) {
        throw new TvdbException(e.getMessage() + " " + urlString, e);
    }
}

From source file:com.brq.wallet.bitid.BitIdAuthenticator.java

License:Microsoft Reference Source License

public BitIdResponse queryServer() {
    final BitIdResponse bitIdResponse = new BitIdResponse();
    final SignedMessage signature = privateKey.signMessage(request.getFullUri());
    try {//from   ww  w . j a  va 2 s .c o m
        OkHttpClient client = getOkHttpClient();
        Request request = getRequest(signature);
        Response callResponse = client.newCall(request).execute();

        bitIdResponse.code = callResponse.code();

        if (bitIdResponse.code >= 200 && bitIdResponse.code < 300) {
            bitIdResponse.status = BitIdResponse.ResponseStatus.SUCCESS;
            bitIdResponse.message = callResponse.body().string();
        } else {
            bitIdResponse.status = BitIdResponse.ResponseStatus.ERROR;
            bitIdResponse.message = formatErrorMessage(callResponse.body().string());

        }

    } catch (SocketTimeoutException e) {
        //connection timed out
        bitIdResponse.status = BitIdResponse.ResponseStatus.TIMEOUT;
    } catch (InterruptedIOException e) {
        //seems like this can also happen when a timeout occurs
        bitIdResponse.status = BitIdResponse.ResponseStatus.TIMEOUT;
    } catch (UnknownHostException e) {
        //host not known, most probably the device has no internet connection
        bitIdResponse.status = BitIdResponse.ResponseStatus.NOCONNECTION;
    } catch (ConnectException e) {
        //might be a refused connection
        bitIdResponse.status = BitIdResponse.ResponseStatus.REFUSED;
    } catch (SSLException e) {
        Preconditions.checkState(enforceSslCorrectness);
        //ask user whether he wants to proceed although there is a problem with the certificate
        bitIdResponse.message = e.getLocalizedMessage();
        bitIdResponse.status = BitIdResponse.ResponseStatus.SSLPROBLEM;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return bitIdResponse;
}

From source file:com.camel.crawler.WebCrawler.java

License:Open Source License

public void fetchWeb(String url) throws IOException {
    client.setConnectTimeout(2, TimeUnit.SECONDS);
    Request request = new Request.Builder().url(url).build();
    Response response = client.newCall(request).execute();

    int responseCode = response.code();

    if (responseCode == 200) {
        extraInfo(response.body().string());
    } else {//w  w  w  .j  ava 2 s . c  o  m
        System.out.println("got error page");
    }
}

From source file:com.cdancy.artifactory.rest.config.ArtifactoryOkHttpCommandExecutorService.java

License:Apache License

@Override
protected HttpResponse invoke(Request nativeRequest) throws IOException, InterruptedException {

    OkHttpClient requestScopedClient = clientSupplier.get();
    requestScopedClient.setProxy(proxyForURI.apply(nativeRequest.uri()));
    Response response = requestScopedClient.newCall(nativeRequest).execute();

    HttpResponse.Builder<?> builder = HttpResponse.builder();
    builder.statusCode(response.code());
    builder.message(response.message());

    Builder<String, String> headerBuilder = ImmutableMultimap.builder();
    Headers responseHeaders = response.headers();

    // Check for Artifactory header and init potential file for downstream use
    File destinationFile = null;/*w w w.  j  a  va2 s.c  om*/
    String artFileName = responseHeaders.get("X-Artifactory-Filename");
    if (artFileName != null) {

        GAVCoordinates gavCoordinates = ArtifactoryUtils.gavFromURL(nativeRequest.url(),
                endpoint.get().toURL());
        destinationFile = ArtifactoryUtils.getGradleFile(gavCoordinates, artFileName,
                responseHeaders.get("ETag"));
        headerBuilder.put(ArtifactoryUtils.LOCATION_HEADER, destinationFile.getAbsolutePath());
    }

    for (String header : responseHeaders.names()) {
        headerBuilder.putAll(header, responseHeaders.values(header));
    }

    ImmutableMultimap<String, String> headers = headerBuilder.build();

    if (response.code() == 204 && response.body() != null) {
        response.body().close();
    } else {
        if (destinationFile != null) {
            if (!destinationFile.exists() || (destinationFile.length() != response.body().contentLength())) {
                InputStream inputStream = null;
                try {
                    inputStream = response.body().byteStream();
                    ArtifactoryUtils.resolveInputStream(inputStream, destinationFile);
                } catch (Exception e) {
                    Throwables.propagate(e);
                } finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                }
            }
            IOUtils.closeQuietly(response.body().byteStream());
        } else {
            Payload payload = newInputStreamPayload(response.body().byteStream());
            contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers);
            builder.payload(payload);
        }
    }

    builder.headers(filterOutContentHeaders(headers));
    return builder.build();
}

From source file:com.cinchapi.concourse.http.HttpLoginTest.java

License:Apache License

@Test
public void testLogin() {
    Response resp = login();
    Assert.assertEquals(200, resp.code());
    JsonObject body = (JsonObject) bodyAsJson(resp);
    Assert.assertEquals("default", body.get("environment").getAsString());
}

From source file:com.cinchapi.concourse.http.HttpLoginTest.java

License:Apache License

@Test
public void testLoginNonDefaultEnvironment() {
    String environment = TestData.getStringNoDigits().replaceAll(" ", "");
    Response resp = login(environment);
    Assert.assertEquals(200, resp.code());
    JsonObject body = (JsonObject) bodyAsJson(resp);
    Assert.assertEquals(environment, body.get("environment").getAsString());
}

From source file:com.cinchapi.concourse.http.HttpLoginTest.java

License:Apache License

@Test
public void testLoginWithMalformedCredSyntaxThrowsAppropriateError() {
    Response resp = post("/login", "{'user': 'admin', 'pass': 'admin'}");
    JsonObject body = (JsonObject) bodyAsJson(resp);
    Assert.assertEquals(resp.code(), BadLoginSyntaxError.INSTANCE.getCode());
    Assert.assertEquals(body.get("error").getAsString(), BadLoginSyntaxError.INSTANCE.getMessage());
}

From source file:com.cinchapi.concourse.http.HttpLoginTest.java

License:Apache License

@Test
public void testLoginAndUseAuthTokenHeader() {
    Response resp = login();
    JsonObject body = (JsonObject) bodyAsJson(resp);
    String token = body.get("token").getAsString();
    clearClientCookies();/*from   w  w  w . j a va2s .co  m*/
    Headers headers = new Headers.Builder().add(GlobalState.HTTP_AUTH_TOKEN_HEADER, token).build();
    resp = get("/", headers);
    Assert.assertEquals(200, resp.code());
}

From source file:com.cinchapi.concourse.http.RestAuditTest.java

License:Apache License

@Test
public void testAuditKeyReturns400Error() {
    Response resp = get("/foo/audit");
    Assert.assertEquals(400, resp.code());
}

From source file:com.cinchapi.concourse.http.RestWriteTest.java

License:Apache License

@Test
public void testInsertJsonInRecord() {
    long record = TestData.getLong();
    JsonObject json = new JsonObject();
    json.addProperty("boolean", true);
    json.addProperty("number", TestData.getScaleCount());
    json.addProperty("string", TestData.getSimpleString());
    Response resp = post("/{0}", json.toString(), record);
    boolean body = bodyAsJava(resp, TypeToken.get(Boolean.class));
    Assert.assertTrue(body);//from  www  .  j av a 2s  .c  o  m
    Assert.assertEquals(200, resp.code());
    Assert.assertEquals(json.get("boolean").getAsBoolean(), client.get("boolean", record));
    Assert.assertEquals(json.get("number").getAsNumber(), client.get("number", record));
    Assert.assertEquals(json.get("string").getAsString(), client.get("string", record));

}