Search in sources :

Example 21 with Builder

use of okhttp3.FormBody.Builder in project BBS-Android by bdpqchen.

the class CollectionClient method getUnSaveBuilder.

private static OkHttpClient.Builder getUnSaveBuilder() {
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(sslSocketFactory);
        builder.hostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return builder;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) SSLSession(javax.net.ssl.SSLSession) SSLContext(javax.net.ssl.SSLContext) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 22 with Builder

use of okhttp3.FormBody.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 23 with Builder

use of okhttp3.FormBody.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 24 with Builder

use of okhttp3.FormBody.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 25 with Builder

use of okhttp3.FormBody.Builder in project YhLibraryForAndroid by android-coco.

the class LoggerInterceptor method logForResponse.

private Response logForResponse(Response response, long duration) {
    try {
        // ===>response LogUtils
        LogUtils.e(tag, "============服务器回复'LogUtils============开始");
        Response.Builder builder = response.newBuilder();
        Response clone = builder.build();
        LogUtils.e(tag, "请求url : " + clone.request().url());
        LogUtils.e(tag, "请求code : " + clone.code());
        LogUtils.e(tag, "请求协议protocol : " + clone.protocol());
        if (!TextUtils.isEmpty(clone.message())) {
            LogUtils.e(tag, "是否成功 : " + clone.message());
            if (showResponse) {
                ResponseBody body = clone.body();
                if (body != null) {
                    MediaType mediaType = body.contentType();
                    if (mediaType != null) {
                        LogUtils.e(tag, "响应主体的类型 : " + mediaType.toString());
                        if (isText(mediaType)) {
                            String resp = body.string();
                            LogUtils.e(tag, "响应主体的内容 : " + resp);
                            body = ResponseBody.create(mediaType, resp);
                            LogUtils.e(tag, "============服务器回复'LogUtils==========结束" + duration + "毫秒");
                            return response.newBuilder().body(body).build();
                        } else {
                            LogUtils.e(tag, "响应主体的内容 : " + " 也许[文件部分],太大了太大了,忽略了!");
                        }
                    }
                }
            }
        }
        LogUtils.e(tag, "============服务器回复'LogUtils==========结束" + duration + "毫秒");
    } catch (Exception e) {
        LogUtils.e(tag, "============服务器回复打印异常:" + e.getMessage());
    }
    return response;
}
Also used : Response(okhttp3.Response) MediaType(okhttp3.MediaType) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody)

Aggregations

Request (okhttp3.Request)190 Response (okhttp3.Response)133 OkHttpClient (okhttp3.OkHttpClient)128 IOException (java.io.IOException)100 RequestBody (okhttp3.RequestBody)77 Test (org.junit.Test)68 File (java.io.File)42 HttpUrl (okhttp3.HttpUrl)40 MultipartBody (okhttp3.MultipartBody)40 Map (java.util.Map)34 MockResponse (okhttp3.mockwebserver.MockResponse)32 Call (okhttp3.Call)29 Retrofit (retrofit2.Retrofit)29 Interceptor (okhttp3.Interceptor)28 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)26 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)25 Builder (okhttp3.OkHttpClient.Builder)24 ResponseBody (okhttp3.ResponseBody)21 Provides (dagger.Provides)20 FormBody (okhttp3.FormBody)20