Search in sources :

Example 21 with Builder

use of okhttp3.MultipartBody.Builder in project MantaroBot by Mantaro.

the class PlayerCmds method applyBadge.

private void applyBadge(MessageChannel channel, Badge badge, User author, EmbedBuilder builder) {
    if (badge == null) {
        channel.sendMessage(builder.build()).queue();
        return;
    }
    Message message = new MessageBuilder().setEmbed(builder.setThumbnail("attachment://avatar.png").build()).build();
    byte[] bytes;
    try {
        String url = author.getEffectiveAvatarUrl();
        if (url.endsWith(".gif")) {
            url = url.substring(0, url.length() - 3) + "png";
        }
        Response res = client.newCall(new Request.Builder().url(url).addHeader("User-Agent", MantaroInfo.USER_AGENT).build()).execute();
        ResponseBody body = res.body();
        if (body == null)
            throw new IOException("body is null");
        bytes = body.bytes();
        res.close();
    } catch (IOException e) {
        throw new AssertionError("io error", e);
    }
    channel.sendFile(badge.apply(bytes), "avatar.png", message).queue();
}
Also used : Response(okhttp3.Response) MessageBuilder(net.dv8tion.jda.core.MessageBuilder) Request(okhttp3.Request) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody)

Example 22 with Builder

use of okhttp3.MultipartBody.Builder in project MantaroBot by Mantaro.

the class WeebAPIRequester method request.

private String request(String endpoint, String e) {
    try {
        StringBuilder builder = new StringBuilder(endpoint);
        if (e != null) {
            builder.append("?");
            builder.append(e);
        }
        Request r = new Request.Builder().url(API_BASE_URL + builder.toString()).addHeader("User-Agent", MantaroInfo.USER_AGENT).addHeader("Authorization", AUTH_HEADER).build();
        Response r1 = httpClient.newCall(r).execute();
        String response = r1.body().string();
        r1.close();
        return response;
    } catch (Exception ex) {
        log.error("Error getting image from weeb.sh", ex);
        return null;
    }
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request)

Example 23 with Builder

use of okhttp3.MultipartBody.Builder in project instructure-android by instructure.

the class RequestInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    Request.Builder builder = request.newBuilder();
    final String token = ApiPrefs.getToken();
    final String userAgent = ApiPrefs.getUserAgent();
    final String domain = ApiPrefs.getFullDomain();
    /* Nearly all requests are instantiated using RestBuilder and will have been tagged with
        a RestParams instance. Here we will attempt to retrieve it, but if unsuccessful we will
        fall back to a new RestParams instance with default values. */
    RestParams params;
    if (request.tag() != null && request.tag() instanceof RestParams) {
        params = (RestParams) request.tag();
    } else {
        params = new RestParams.Builder().build();
    }
    // Set the UserAgent
    if (!userAgent.equals("")) {
        builder.addHeader("User-Agent", userAgent);
    }
    // Authenticate if possible
    if (!params.shouldIgnoreToken() && !token.equals("")) {
        builder.addHeader("Authorization", "Bearer " + token);
    }
    // Add Accept-Language header for a11y
    builder.addHeader("accept-language", getAcceptedLanguageString());
    if (!APIHelper.hasNetworkConnection() || params.isForceReadFromCache()) {
        // Offline or only want cached data
        builder.cacheControl(CacheControl.FORCE_CACHE);
    } else if (params.isForceReadFromNetwork()) {
        // Typical from a pull-to-refresh
        builder.cacheControl(CacheControl.FORCE_NETWORK);
    }
    // Fun Fact: HTTP referer (originally a misspelling of referrer) is an HTTP header field that identifies
    // the address of the webpage that linked to the resource being requested
    // Source: https://en.wikipedia.org/wiki/HTTP_referer
    // Institutions need the referrer for a variety of reasons - mostly for restricted content
    // Strip out non-ascii characters, otherwise addHeader may throw an exception
    builder.addHeader("Referer", domain.replaceAll("[^\\x20-\\x7e]", ""));
    request = builder.build();
    // Masquerade if necessary
    if (ApiPrefs.isMasquerading()) {
        HttpUrl url = request.url().newBuilder().addQueryParameter("as_user_id", Long.toString(ApiPrefs.getMasqueradeId())).build();
        request = request.newBuilder().url(url).build();
    }
    if (params.usePerPageQueryParam()) {
        HttpUrl url = request.url().newBuilder().addQueryParameter("per_page", Integer.toString(ApiPrefs.getPerPageCount())).build();
        request = request.newBuilder().url(url).build();
    }
    return chain.proceed(request);
}
Also used : RestParams(com.instructure.canvasapi2.builders.RestParams) Request(okhttp3.Request) HttpUrl(okhttp3.HttpUrl)

Example 24 with Builder

use of okhttp3.MultipartBody.Builder in project hub-fortify-ssc-integration-service by blackducksoftware.

the class FortifyService method getHeader.

public static Builder getHeader(String userName, String password) {
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(Level.BASIC);
    OkHttpClient.Builder okBuilder = new OkHttpClient.Builder();
    okBuilder.authenticator(new Authenticator() {

        @Override
        public Request authenticate(Route route, Response response) throws IOException {
            String credential = Credentials.basic(userName, password);
            if (credential.equals(response.request().header("Authorization"))) {
                try {
                    FortifyExceptionUtil.verifyFortifyResponseCode(response.code(), "Unauthorized access of Fortify Api");
                } catch (IntegrationException e) {
                    throw new IOException(e);
                }
                return null;
            }
            return response.request().newBuilder().header("Authorization", credential).build();
        }
    });
    okBuilder.addInterceptor(logging);
    return okBuilder;
}
Also used : Builder(okhttp3.OkHttpClient.Builder) Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) IntegrationException(com.blackducksoftware.integration.exception.IntegrationException) Builder(okhttp3.OkHttpClient.Builder) Request(okhttp3.Request) IOException(java.io.IOException) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Authenticator(okhttp3.Authenticator) Route(okhttp3.Route)

Example 25 with Builder

use of okhttp3.MultipartBody.Builder in project Fast-Android-Networking by amitshekhariitbhu.

the class Rx2InternalNetworking method generateSimpleObservable.

public static <T> Observable<T> generateSimpleObservable(Rx2ANRequest request) {
    Request okHttpRequest;
    Request.Builder builder = new Request.Builder().url(request.getUrl());
    InternalNetworking.addHeadersToRequestBuilder(builder, request);
    RequestBody requestBody;
    switch(request.getMethod()) {
        case GET:
            {
                builder = builder.get();
                break;
            }
        case POST:
            {
                requestBody = request.getRequestBody();
                builder = builder.post(requestBody);
                break;
            }
        case PUT:
            {
                requestBody = request.getRequestBody();
                builder = builder.put(requestBody);
                break;
            }
        case DELETE:
            {
                requestBody = request.getRequestBody();
                builder = builder.delete(requestBody);
                break;
            }
        case HEAD:
            {
                builder = builder.head();
                break;
            }
        case OPTIONS:
            {
                builder = builder.method(ANConstants.OPTIONS, null);
                break;
            }
        case PATCH:
            {
                requestBody = request.getRequestBody();
                builder = builder.patch(requestBody);
                break;
            }
    }
    if (request.getCacheControl() != null) {
        builder.cacheControl(request.getCacheControl());
    }
    okHttpRequest = builder.build();
    if (request.getOkHttpClient() != null) {
        request.setCall(request.getOkHttpClient().newBuilder().cache(InternalNetworking.sHttpClient.cache()).build().newCall(okHttpRequest));
    } else {
        request.setCall(InternalNetworking.sHttpClient.newCall(okHttpRequest));
    }
    return new SimpleANObservable<>(request);
}
Also used : Request(okhttp3.Request) RequestBody(okhttp3.RequestBody)

Aggregations

Request (okhttp3.Request)410 OkHttpClient (okhttp3.OkHttpClient)359 Response (okhttp3.Response)287 IOException (java.io.IOException)221 RequestBody (okhttp3.RequestBody)172 HttpUrl (okhttp3.HttpUrl)109 MultipartBody (okhttp3.MultipartBody)102 File (java.io.File)93 Test (org.junit.Test)92 Map (java.util.Map)91 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)87 Call (okhttp3.Call)77 HashMap (java.util.HashMap)63 AndroidFlipperClient (com.facebook.flipper.android.AndroidFlipperClient)59 FlipperClient (com.facebook.flipper.core.FlipperClient)59 DatabasesFlipperPlugin (com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin)59 FrescoFlipperPlugin (com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin)59 InspectorFlipperPlugin (com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin)59 NetworkFlipperPlugin (com.facebook.flipper.plugins.network.NetworkFlipperPlugin)59 ReactFlipperPlugin (com.facebook.flipper.plugins.react.ReactFlipperPlugin)59