Example usage for com.squareup.okhttp Request method

List of usage examples for com.squareup.okhttp Request method

Introduction

In this page you can find the example usage for com.squareup.okhttp Request method.

Prototype

String method

To view the source code for com.squareup.okhttp Request method.

Click Source Link

Usage

From source file:org.graylog2.rest.RemoteInterfaceProvider.java

License:Open Source License

public <T> T get(Node node, final String authorizationToken, Class<T> interfaceClass) {
    final OkHttpClient okHttpClient = this.okHttpClient.clone();
    okHttpClient.interceptors().add(new Interceptor() {
        @Override/*  w w  w .  j  ava 2s .  co m*/
        public Response intercept(Interceptor.Chain chain) throws IOException {
            final Request original = chain.request();

            Request.Builder builder = original.newBuilder().header("Accept", "application/json")
                    .method(original.method(), original.body());

            if (authorizationToken != null) {
                builder = builder.header("Authorization", authorizationToken);
            }

            return chain.proceed(builder.build());
        }
    });
    final Retrofit retrofit = new Retrofit.Builder().baseUrl(node.getTransportAddress())
            .addConverterFactory(JacksonConverterFactory.create(objectMapper)).client(okHttpClient).build();

    return retrofit.create(interfaceClass);
}

From source file:org.kegbot.api.KegbotApiImpl.java

License:Open Source License

private JsonNode requestJson(Request request) throws KegbotApiException {
    final Response response;
    final long startTime = SystemClock.elapsedRealtime();
    try {/*from w  w w . j  a v a2s  .  c o m*/
        response = mClient.newCall(request).execute();
    } catch (IOException e) {
        Log.w(TAG, String.format("--> %s %s [ERR]", request.method(), request.urlString()));
        throw new KegbotApiException(e);
    }
    final long endTime = SystemClock.elapsedRealtime();

    final int responseCode = response.code();
    final String logMessage = String.format("--> %s %s [%s] %sms", request.method(), request.urlString(),
            responseCode, endTime - startTime);
    if (responseCode >= 200 && responseCode < 300) {
        Log.d(TAG, logMessage);
    } else {
        Log.w(TAG, logMessage);
    }
    final ResponseBody body = response.body();

    final JsonNode rootNode;
    try {
        try {
            final ObjectMapper mapper = new ObjectMapper();
            rootNode = mapper.readValue(body.byteStream(), JsonNode.class);
        } finally {
            body.close();
        }
    } catch (JsonParseException e) {
        throw new KegbotApiMalformedResponseException(e);
    } catch (JsonMappingException e) {
        throw new KegbotApiMalformedResponseException(e);
    } catch (IOException e) {
        throw new KegbotApiException(e);
    }

    boolean success = false;
    try {
        // Handle structural errors.
        if (!rootNode.has("meta")) {
            throw new KegbotApiMalformedResponseException("Response is missing 'meta' field.");
        }
        final JsonNode meta = rootNode.get("meta");
        if (!meta.isContainerNode()) {
            throw new KegbotApiMalformedResponseException("'meta' field is wrong type.");
        }

        final String message;
        if (rootNode.has("error") && rootNode.get("error").has("message")) {
            message = rootNode.get("error").get("message").getTextValue();
        } else {
            message = null;
        }

        // Handle HTTP errors.
        if (responseCode < 200 || responseCode >= 400) {
            switch (responseCode) {
            case 401:
                throw new NotAuthorizedException(message);
            case 404:
                throw new KegbotApi404(message);
            case 405:
                throw new MethodNotAllowedException(message);
            default:
                if (message != null) {
                    throw new KegbotApiServerError(message);
                } else {
                    throw new KegbotApiServerError("Server error, response code=" + responseCode);
                }
            }
        }

        success = true;
        return rootNode;
    } finally {
        if (!success) {
            Log.d(TAG, "Response JSON was: " + rootNode.toString());
        }
    }
}

From source file:retrofit.MagnetRestAdapter.java

License:Apache License

@Override
public boolean isAuthRequired(Request request) {
    if ("POST".equals(request.method()) && (request.urlString().endsWith(RestConstants.APP_LOGIN_URL)
            || request.urlString().endsWith(RestConstants.APP_LOGIN_WITH_DEVICE_URL)
            || request.urlString().endsWith(RestConstants.USER_REFRESH_TOKEN_URL))) {
        return false;
    }//from   w  w w  .  j  ava  2 s. c  o m
    return true;
}

From source file:syncthing.api.SyncthingApiInterceptor.java

License:Open Source License

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    if (!StringUtils.isEmpty(config.getApiKey())) {
        request = request.newBuilder()//from w  ww  .jav  a2 s  .  co  m
                .addHeader(SyncthingApi.HEADER_API_KEY, StringUtils.trim(config.getApiKey())).build();
    } else if (!StringUtils.isEmpty(config.getAuth())) {
        request = request.newBuilder().addHeader("Authorization", StringUtils.trim(config.getAuth())).build();
    }
    if (config.isDebug()) {
        Timber.d(request.toString());
        if (StringUtils.equalsIgnoreCase(request.method(), "POST")) {
            Buffer buffer = new Buffer();
            request.body().writeTo(buffer);
            ByteString content = buffer.snapshot();
            Timber.d("body=%s", buffer.readString(Charset.defaultCharset()));
            MediaType type = request.body().contentType();
            request = request.newBuilder().post(RequestBody.create(type, content)).build();
        }
    }
    return chain.proceed(request);
}