Search in sources :

Example 46 with Request

use of com.tonyodev.fetch2.Request in project WordPress-Android by wordpress-mobile.

the class GravatarApi method createClient.

private static OkHttpClient createClient(final String accessToken) {
    OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
    //// uncomment the following line to add logcat logging
    //httpClientBuilder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
    // add oAuth token usage
    httpClientBuilder.addInterceptor(new Interceptor() {

        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Request original = chain.request();
            Request.Builder requestBuilder = original.newBuilder().header("Authorization", "Bearer " + accessToken).method(original.method(), original.body());
            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    });
    return httpClientBuilder.build();
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) Interceptor(okhttp3.Interceptor)

Example 47 with Request

use of com.tonyodev.fetch2.Request in project Lightning-Browser by anthonycr.

the class BaseSuggestionsModel method downloadSuggestionsForQuery.

/**
     * This method downloads the search suggestions for the specific query.
     * NOTE: This is a blocking operation, do not getResults on the UI thread.
     *
     * @param query the query to get suggestions for
     * @return the cache file containing the suggestions
     */
@Nullable
private InputStream downloadSuggestionsForQuery(@NonNull String query, @NonNull String language) {
    String queryUrl = createQueryUrl(query, language);
    try {
        URL url = new URL(queryUrl);
        // OkHttp automatically gzips requests
        Request suggestionsRequest = new Request.Builder().url(url).addHeader("Accept-Charset", mEncoding).cacheControl(mCacheControl).build();
        Response suggestionsResponse = mHttpClient.newCall(suggestionsRequest).execute();
        ResponseBody responseBody = suggestionsResponse.body();
        return responseBody != null ? responseBody.byteStream() : null;
    } catch (IOException exception) {
        Log.e(TAG, "Problem getting search suggestions", exception);
    }
    return null;
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) IOException(java.io.IOException) URL(java.net.URL) ResponseBody(okhttp3.ResponseBody) Nullable(android.support.annotation.Nullable)

Example 48 with Request

use of com.tonyodev.fetch2.Request in project ignite by apache.

the class RestExecutor method sendRequest.

/** */
private RestResult sendRequest(boolean demo, String path, Map<String, Object> params, String mtd, Map<String, Object> headers, String body) throws IOException {
    if (demo && AgentClusterDemo.getDemoUrl() == null) {
        try {
            AgentClusterDemo.tryStart().await();
        } catch (InterruptedException ignore) {
            throw new IllegalStateException("Failed to execute request because of embedded node for demo mode is not started yet.");
        }
    }
    String url = demo ? AgentClusterDemo.getDemoUrl() : nodeUrl;
    HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
    if (path != null)
        urlBuilder.addPathSegment(path);
    final Request.Builder reqBuilder = new Request.Builder();
    if (headers != null) {
        for (Map.Entry<String, Object> entry : headers.entrySet()) if (entry.getValue() != null)
            reqBuilder.addHeader(entry.getKey(), entry.getValue().toString());
    }
    if ("GET".equalsIgnoreCase(mtd)) {
        if (params != null) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (entry.getValue() != null)
                    urlBuilder.addQueryParameter(entry.getKey(), entry.getValue().toString());
            }
        }
    } else if ("POST".equalsIgnoreCase(mtd)) {
        if (body != null) {
            MediaType contentType = MediaType.parse("text/plain");
            reqBuilder.post(RequestBody.create(contentType, body));
        } else {
            FormBody.Builder formBody = new FormBody.Builder();
            if (params != null) {
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    if (entry.getValue() != null)
                        formBody.add(entry.getKey(), entry.getValue().toString());
                }
            }
            reqBuilder.post(formBody.build());
        }
    } else
        throw new IllegalArgumentException("Unknown HTTP-method: " + mtd);
    reqBuilder.url(urlBuilder.build());
    try (Response resp = httpClient.newCall(reqBuilder.build()).execute()) {
        String content = resp.body().string();
        if (resp.isSuccessful()) {
            JsonNode node = mapper.readTree(content);
            int status = node.get("successStatus").asInt();
            switch(status) {
                case STATUS_SUCCESS:
                    return RestResult.success(node.get("response").toString());
                default:
                    return RestResult.fail(status, node.get("error").asText());
            }
        }
        if (resp.code() == 401)
            return RestResult.fail(STATUS_AUTH_FAILED, "Failed to authenticate in grid. Please check agent\'s login and password or node port.");
        return RestResult.fail(STATUS_FAILED, "Failed connect to node and execute REST command.");
    } catch (ConnectException ignore) {
        throw new ConnectException("Failed connect to node and execute REST command [url=" + urlBuilder + "]");
    }
}
Also used : Request(okhttp3.Request) FormBody(okhttp3.FormBody) JsonNode(com.fasterxml.jackson.databind.JsonNode) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) MediaType(okhttp3.MediaType) HashMap(java.util.HashMap) Map(java.util.Map) ConnectException(java.net.ConnectException)

Example 49 with Request

use of com.tonyodev.fetch2.Request in project realm-java by realm.

the class OkHttpAuthenticationServer method logout.

private LogoutResponse logout(URL logoutUrl, String requestBody) throws Exception {
    Request request = new Request.Builder().url(logoutUrl).addHeader("Content-Type", "application/json").addHeader("Accept", "application/json").post(RequestBody.create(JSON, requestBody)).build();
    Call call = client.newCall(request);
    Response response = call.execute();
    return LogoutResponse.from(response);
}
Also used : Response(okhttp3.Response) Call(okhttp3.Call) Request(okhttp3.Request)

Example 50 with Request

use of com.tonyodev.fetch2.Request in project muzei by romannurik.

the class FeaturedArtSource method fetchJsonObject.

private JSONObject fetchJsonObject(final String url) throws IOException, JSONException {
    OkHttpClient client = new OkHttpClient.Builder().build();
    Request request = new Request.Builder().url(url).build();
    String json = client.newCall(request).execute().body().string();
    JSONTokener tokener = new JSONTokener(json);
    Object val = tokener.nextValue();
    if (!(val instanceof JSONObject)) {
        throw new JSONException("Expected JSON object.");
    }
    return (JSONObject) val;
}
Also used : JSONTokener(org.json.JSONTokener) OkHttpClient(okhttp3.OkHttpClient) JSONObject(org.json.JSONObject) Request(okhttp3.Request) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject)

Aggregations

Request (okhttp3.Request)1617 Response (okhttp3.Response)1022 IOException (java.io.IOException)525 Test (org.junit.Test)407 OkHttpClient (okhttp3.OkHttpClient)331 RequestBody (okhttp3.RequestBody)256 Call (okhttp3.Call)239 ResponseBody (okhttp3.ResponseBody)189 HttpUrl (okhttp3.HttpUrl)146 Callback (okhttp3.Callback)109 Map (java.util.Map)85 File (java.io.File)77 InputStream (java.io.InputStream)77 JSONObject (org.json.JSONObject)76 MediaType (okhttp3.MediaType)75 Buffer (okio.Buffer)73 List (java.util.List)71 Headers (okhttp3.Headers)71 FormBody (okhttp3.FormBody)64 HashMap (java.util.HashMap)63