Search in sources :

Example 31 with Builder

use of okhttp3.FormBody.Builder in project PocketMaps by junjunguo.

the class HttpConnection method getOkHttpClient.

private static OkHttpClient getOkHttpClient() {
    if (client == null) {
        Builder b = new Builder();
        b.connectTimeout(TIMEOUT_CONNECTION, TimeUnit.MILLISECONDS);
        b.readTimeout(TIMEOUT_SOCKET, TimeUnit.MILLISECONDS);
        client = b.build();
    /*
            client.setConnectTimeout(TIMEOUT_CONNECTION, TimeUnit.MILLISECONDS);
            client.setReadTimeout(TIMEOUT_SOCKET, TimeUnit.MILLISECONDS);
            */
    }
    return client;
}
Also used : Builder(okhttp3.OkHttpClient.Builder)

Example 32 with Builder

use of okhttp3.FormBody.Builder in project android-diplicity by zond.

the class RetrofitActivity method recreateServices.

protected void recreateServices() {
    AuthenticatingCallAdapterFactory adapterFactory = new AuthenticatingCallAdapterFactory();
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.addInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request toIssue = chain.request().newBuilder().addHeader("Accept", "application/json; charset=UTF-8").addHeader("X-Diplicity-API-Level", "" + DIPLICITY_API_LEVEL).build();
            if (getLocalDevelopmentMode() && !getLocalDevelopmentModeFakeID().equals("")) {
                HttpUrl url = toIssue.url().newBuilder().addQueryParameter("fake-id", getLocalDevelopmentModeFakeID()).build();
                toIssue = toIssue.newBuilder().url(url).build();
            } else if (!getAuthToken().equals("")) {
                toIssue = toIssue.newBuilder().addHeader("Authorization", "bearer " + getAuthToken()).build();
            }
            Log.d("Diplicity", "" + toIssue.method() + "ing " + toIssue.url());
            return chain.proceed(toIssue);
        }
    });
    builder.connectTimeout(10, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS).readTimeout(10, TimeUnit.SECONDS);
    Gson gson = new GsonBuilder().registerTypeAdapter(Ticker.class, new TickerUnserializer()).registerTypeAdapter(Game.class, new GameUnserializer(this)).create();
    Retrofit retrofit = new Retrofit.Builder().baseUrl(getBaseURL()).addConverterFactory(GsonConverterFactory.create(gson)).addCallAdapterFactory(adapterFactory).client(builder.build()).build();
    gameService = retrofit.create(GameService.class);
    userStatsService = retrofit.create(UserStatsService.class);
    memberService = retrofit.create(MemberService.class);
    rootService = retrofit.create(RootService.class);
    variantService = retrofit.create(VariantService.class);
    optionsService = retrofit.create(OptionsService.class);
    orderService = retrofit.create(OrderService.class);
    phaseService = retrofit.create(PhaseService.class);
    channelService = retrofit.create(ChannelService.class);
    messageService = retrofit.create(MessageService.class);
    phaseResultService = retrofit.create(PhaseResultService.class);
    gameResultService = retrofit.create(GameResultService.class);
    phaseStateService = retrofit.create(PhaseStateService.class);
    gameStateService = retrofit.create(GameStateService.class);
    userConfigService = retrofit.create(UserConfigService.class);
    banService = retrofit.create(BanService.class);
}
Also used : OkHttpClient(okhttp3.OkHttpClient) GsonBuilder(com.google.gson.GsonBuilder) Gson(com.google.gson.Gson) PhaseService(se.oort.diplicity.apigen.PhaseService) GameStateService(se.oort.diplicity.apigen.GameStateService) PhaseResultService(se.oort.diplicity.apigen.PhaseResultService) BanService(se.oort.diplicity.apigen.BanService) Interceptor(okhttp3.Interceptor) GsonBuilder(com.google.gson.GsonBuilder) MemberService(se.oort.diplicity.apigen.MemberService) Request(okhttp3.Request) UserConfigService(se.oort.diplicity.apigen.UserConfigService) IOException(java.io.IOException) TickerUnserializer(se.oort.diplicity.apigen.TickerUnserializer) GameResultService(se.oort.diplicity.apigen.GameResultService) UserStatsService(se.oort.diplicity.apigen.UserStatsService) HttpUrl(okhttp3.HttpUrl) MessageService(se.oort.diplicity.apigen.MessageService) PhaseStateService(se.oort.diplicity.apigen.PhaseStateService) Response(okhttp3.Response) Retrofit(retrofit2.Retrofit) Game(se.oort.diplicity.apigen.Game) GameService(se.oort.diplicity.apigen.GameService) OrderService(se.oort.diplicity.apigen.OrderService)

Example 33 with Builder

use of okhttp3.FormBody.Builder in project AndroidStudy by tinggengyan.

the class UnsafeOkHttpClient method getUnsafeOkHttpClient.

public static OkHttpClient getUnsafeOkHttpClient() {
    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) throws CertificateException {
            }

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

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        // 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 SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        OkHttpClient okHttpClient = new OkHttpClient();
        OkHttpClient.Builder builder = okHttpClient.newBuilder();
        builder.sslSocketFactory(sslSocketFactory);
        builder.protocols(Arrays.asList(Protocol.HTTP_1_1));
        builder.hostnameVerifier(new HostnameVerifier() {

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

Example 34 with Builder

use of okhttp3.FormBody.Builder in project retrofit by square.

the class RequestBuilder method build.

Request build() {
    HttpUrl url;
    HttpUrl.Builder urlBuilder = this.urlBuilder;
    if (urlBuilder != null) {
        url = urlBuilder.build();
    } else {
        // No query parameters triggered builder creation, just combine the relative URL and base URL.
        // noinspection ConstantConditions Non-null if urlBuilder is null.
        url = baseUrl.resolve(relativeUrl);
        if (url == null) {
            throw new IllegalArgumentException("Malformed URL. Base: " + baseUrl + ", Relative: " + relativeUrl);
        }
    }
    RequestBody body = this.body;
    if (body == null) {
        // Try to pull from one of the builders.
        if (formBuilder != null) {
            body = formBuilder.build();
        } else if (multipartBuilder != null) {
            body = multipartBuilder.build();
        } else if (hasBody) {
            // Body is absent, make an empty body.
            body = RequestBody.create(null, new byte[0]);
        }
    }
    MediaType contentType = this.contentType;
    if (contentType != null) {
        if (body != null) {
            body = new ContentTypeOverridingRequestBody(body, contentType);
        } else {
            requestBuilder.addHeader("Content-Type", contentType.toString());
        }
    }
    return requestBuilder.url(url).method(method, body).build();
}
Also used : MediaType(okhttp3.MediaType) HttpUrl(okhttp3.HttpUrl) RequestBody(okhttp3.RequestBody)

Example 35 with Builder

use of okhttp3.FormBody.Builder in project nifi-minifi by apache.

the class PullHttpChangeIngestor method run.

@Override
public void run() {
    try {
        logger.debug("Attempting to pull new config");
        HttpUrl.Builder builder = new HttpUrl.Builder().host(hostReference.get()).port(portReference.get()).encodedPath(pathReference.get());
        String query = queryReference.get();
        if (!StringUtil.isNullOrEmpty(query)) {
            builder = builder.encodedQuery(query);
        }
        final HttpUrl url = builder.scheme(connectionScheme).build();
        final Request.Builder requestBuilder = new Request.Builder().get().url(url);
        if (useEtag) {
            requestBuilder.addHeader("If-None-Match", lastEtag);
        }
        final Request request = requestBuilder.build();
        final OkHttpClient httpClient = httpClientReference.get();
        final Call call = httpClient.newCall(request);
        final Response response = call.execute();
        logger.debug("Response received: {}", response.toString());
        int code = response.code();
        if (code == NOT_MODIFIED_STATUS_CODE) {
            return;
        }
        if (code >= 400) {
            throw new IOException("Got response code " + code + " while trying to pull configuration: " + response.body().string());
        }
        ResponseBody body = response.body();
        if (body == null) {
            logger.warn("No body returned when pulling a new configuration");
            return;
        }
        ByteBuffer bodyByteBuffer = ByteBuffer.wrap(body.bytes());
        ByteBuffer readOnlyNewConfig = null;
        // checking if some parts of the configuration must be preserved
        if (overrideSecurity) {
            readOnlyNewConfig = bodyByteBuffer.asReadOnlyBuffer();
        } else {
            logger.debug("Preserving previous security properties...");
            // get the current security properties from the current configuration file
            final File configFile = new File(properties.get().getProperty(RunMiNiFi.MINIFI_CONFIG_FILE_KEY));
            ConvertableSchema<ConfigSchema> configSchema = SchemaLoader.loadConvertableSchemaFromYaml(new FileInputStream(configFile));
            ConfigSchema currentSchema = configSchema.convert();
            SecurityPropertiesSchema secProps = currentSchema.getSecurityProperties();
            // override the security properties in the pulled configuration with the previous properties
            configSchema = SchemaLoader.loadConvertableSchemaFromYaml(new ByteBufferInputStream(bodyByteBuffer.duplicate()));
            ConfigSchema newSchema = configSchema.convert();
            newSchema.setSecurityProperties(secProps);
            // return the updated configuration preserving the previous security configuration
            readOnlyNewConfig = ByteBuffer.wrap(new Yaml().dump(newSchema.toMap()).getBytes()).asReadOnlyBuffer();
        }
        if (differentiator.isNew(readOnlyNewConfig)) {
            logger.debug("New change received, notifying listener");
            configurationChangeNotifier.notifyListeners(readOnlyNewConfig);
            logger.debug("Listeners notified");
        } else {
            logger.debug("Pulled config same as currently running.");
        }
        if (useEtag) {
            lastEtag = (new StringBuilder("\"")).append(response.header("ETag").trim()).append("\"").toString();
        }
    } catch (Exception e) {
        logger.warn("Hit an exception while trying to pull", e);
    }
}
Also used : Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) ByteBufferInputStream(org.apache.nifi.minifi.bootstrap.util.ByteBufferInputStream) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) HttpUrl(okhttp3.HttpUrl) FileInputStream(java.io.FileInputStream) Yaml(org.yaml.snakeyaml.Yaml) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) SecurityPropertiesSchema(org.apache.nifi.minifi.commons.schema.SecurityPropertiesSchema) File(java.io.File) ConfigSchema(org.apache.nifi.minifi.commons.schema.ConfigSchema)

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