Search in sources :

Example 21 with Builder

use of okhttp3.HttpUrl.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.HttpUrl.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.HttpUrl.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.HttpUrl.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.HttpUrl.Builder in project samourai-wallet-android by Samourai-Wallet.

the class WebUtil method tor_postURL.

public String tor_postURL(String URL, String jsonToString, Map<String, String> headers) throws Exception {
    final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    RequestBody body = RequestBody.create(JSON, jsonToString);
    OkHttpClient.Builder builder = new OkHttpClient.Builder().proxy(TorManager.getInstance(this.context).getProxy());
    if (URL.contains("onion")) {
        getHostNameVerifier(builder);
    }
    if (BuildConfig.DEBUG) {
        builder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
    }
    Request.Builder rb = new Request.Builder();
    // set headers
    if (headers == null) {
        headers = new HashMap<>();
    }
    for (Map.Entry<String, String> e : headers.entrySet()) {
        rb = rb.header(e.getKey(), e.getValue());
    }
    Request request = rb.url(URL).post(body).build();
    try (Response response = builder.build().newCall(request).execute()) {
        if (response.body() == null) {
            return "";
        }
        return response.body().string();
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) Response(okhttp3.Response) HttpResponse(ch.boye.httpclientandroidlib.HttpResponse) MediaType(okhttp3.MediaType) HashMap(java.util.HashMap) Map(java.util.Map) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) RequestBody(okhttp3.RequestBody)

Aggregations

Request (okhttp3.Request)204 Response (okhttp3.Response)146 OkHttpClient (okhttp3.OkHttpClient)141 IOException (java.io.IOException)111 RequestBody (okhttp3.RequestBody)81 Test (org.junit.Test)75 HttpUrl (okhttp3.HttpUrl)47 File (java.io.File)42 MultipartBody (okhttp3.MultipartBody)40 MockResponse (okhttp3.mockwebserver.MockResponse)40 Map (java.util.Map)39 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)31 Call (okhttp3.Call)29 Interceptor (okhttp3.Interceptor)29 Retrofit (retrofit2.Retrofit)29 Builder (okhttp3.OkHttpClient.Builder)26 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)25 ResponseBody (okhttp3.ResponseBody)24 HashMap (java.util.HashMap)22 FormBody (okhttp3.FormBody)21