Search in sources :

Example 11 with Builder

use of okhttp3.MultipartBody.Builder in project Gradle-demo by Arisono.

the class RetrofitImpl method initClient.

@Override
public void initClient() {
    // 本类保证初始化一次,减少系统开销
    Builder okBuilder = new OkHttpClient.Builder().connectTimeout(mbuilder.getConnectTimeout(), TimeUnit.SECONDS).readTimeout(mbuilder.getReadTimeout(), TimeUnit.SECONDS).writeTimeout(mbuilder.getWriteTimeout(), TimeUnit.SECONDS).sslSocketFactory(OkhttpUtils.createSSLSocketFactory(), // 信任所有证书
    new TrustAllCerts()).hostnameVerifier(new TrustAllHostnameVerifier());
    LogInterceptor logInterceptor = new LogInterceptor();
    logInterceptor.setBuilder(mbuilder);
    okBuilder.addInterceptor(logInterceptor);
    if (mbuilder.getCacheFileSize() != 0) {
        okBuilder.cache(new Cache(mbuilder.getCacheFile(), mbuilder.getCacheFileSize()));
        okBuilder.addInterceptor(new CacheInterceptor(String.valueOf(mbuilder.getCacheTime()), mbuilder.getCacheType()));
    }
    //后期缓存策略改进
    switch(mbuilder.getCacheType()) {
        case CacheType.ONLY_NETWORK:
            OkhttpUtils.println("CacheType.ONLY_NETWORK");
            break;
        case CacheType.ONLY_CACHED:
            OkhttpUtils.println("CacheType.ONLY_CACHED");
            break;
        case CacheType.CACHED_ELSE_NETWORK:
            break;
        case CacheType.NETWORK_ELSE_CACHED:
            break;
        default:
            break;
    }
    OkHttpClient client = okBuilder.build();
    retrofit = new Retrofit.Builder().client(client).baseUrl(mbuilder.getBaseUrl()).addConverterFactory(StringConverterFactory.create()).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
}
Also used : Builder(okhttp3.OkHttpClient.Builder) Retrofit(retrofit2.Retrofit) TrustAllHostnameVerifier(com.gradle.android.retrofit.OkhttpUtils.TrustAllHostnameVerifier) OkHttpClient(okhttp3.OkHttpClient) Builder(okhttp3.OkHttpClient.Builder) LogInterceptor(com.gradle.android.Interceptor.LogInterceptor) CacheInterceptor(com.gradle.android.Interceptor.CacheInterceptor) TrustAllCerts(com.gradle.android.retrofit.OkhttpUtils.TrustAllCerts) Cache(okhttp3.Cache)

Example 12 with Builder

use of okhttp3.MultipartBody.Builder in project Gradle-demo by Arisono.

the class RetrofitUtils method uploads.

public void uploads(Subscriber<Object> s, String url, Map<String, Object> params) {
    MultipartBody.Builder builder = new MultipartBody.Builder();
    builder.setType(MultipartBody.FORM);
    //追加参数
    for (String key : params.keySet()) {
        Object object = params.get(key);
        if (!(object instanceof File)) {
            builder.addFormDataPart(key, object.toString());
        } else {
            File file = (File) object;
            //其中参数“file”和服务器接收的参数 一一对应,保证多文件上传唯一key不变
            builder.addFormDataPart("file", file.getName(), RequestBody.create(null, file));
        }
    }
    //创建RequestBody
    RequestBody body = builder.build();
    Observable<Object> o = paramService.uploads(url, body);
    toSubscribe(o, s);
}
Also used : MultipartBody(okhttp3.MultipartBody) File(java.io.File) RequestBody(okhttp3.RequestBody)

Example 13 with Builder

use of okhttp3.MultipartBody.Builder in project AntennaPod by AntennaPod.

the class GpodnetService method uploadSubscriptions.

/**
     * Uploads the subscriptions of a specific device.
     * <p/>
     * This method requires authentication.
     *
     * @param username      The username. Must be the same user as the one which is
     *                      currently logged in.
     * @param deviceId      The ID of the device whose subscriptions should be updated.
     * @param subscriptions A list of feed URLs containing all subscriptions of the
     *                      device.
     * @throws IllegalArgumentException              If username, deviceId or subscriptions is null.
     * @throws GpodnetServiceAuthenticationException If there is an authentication error.
     */
public void uploadSubscriptions(@NonNull String username, @NonNull String deviceId, @NonNull List<String> subscriptions) throws GpodnetServiceException {
    try {
        URL url = new URI(BASE_SCHEME, BASE_HOST, String.format("/subscriptions/%s/%s.txt", username, deviceId), null).toURL();
        StringBuilder builder = new StringBuilder();
        for (String s : subscriptions) {
            builder.append(s);
            builder.append("\n");
        }
        RequestBody body = RequestBody.create(TEXT, builder.toString());
        Request.Builder request = new Request.Builder().put(body).url(url);
        executeRequest(request);
    } catch (MalformedURLException | URISyntaxException e) {
        e.printStackTrace();
        throw new GpodnetServiceException(e);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) Request(okhttp3.Request) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URL(java.net.URL) RequestBody(okhttp3.RequestBody)

Example 14 with Builder

use of okhttp3.MultipartBody.Builder in project muzei by romannurik.

the class OkHttpClientFactory method enableTls12.

/**
     * Enable TLS on the OKHttp builder by setting a custom SocketFactory
     */
private static OkHttpClient.Builder enableTls12(OkHttpClient.Builder client) {
    Log.i(TAG, "Enabling HTTPS compatibility mode");
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
            throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
        }
        X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
        client.sslSocketFactory(new TLSSocketFactory(), trustManager);
        ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS).tlsVersions(TlsVersion.TLS_1_2, TlsVersion.TLS_1_1).build();
        List<ConnectionSpec> specs = new ArrayList<>();
        specs.add(cs);
        specs.add(ConnectionSpec.COMPATIBLE_TLS);
        specs.add(ConnectionSpec.CLEARTEXT);
        client.connectionSpecs(specs);
    } catch (Exception exc) {
        Log.e(TAG, "Error while setting TLS", exc);
    }
    return client;
}
Also used : ConnectionSpec(okhttp3.ConnectionSpec) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) ArrayList(java.util.ArrayList) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 15 with Builder

use of okhttp3.MultipartBody.Builder in project okhttp by square.

the class URLEncodingTest method backdoorUrlToUri.

private URI backdoorUrlToUri(URL url) throws Exception {
    final AtomicReference<URI> uriReference = new AtomicReference<>();
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    Internal.instance.setCache(builder, new InternalCache() {

        @Override
        public Response get(Request request) throws IOException {
            uriReference.set(request.url().uri());
            throw new UnsupportedOperationException();
        }

        @Override
        public CacheRequest put(Response response) throws IOException {
            return null;
        }

        @Override
        public void remove(Request request) throws IOException {
        }

        @Override
        public void update(Response cached, Response network) {
        }

        @Override
        public void trackConditionalCacheHit() {
        }

        @Override
        public void trackResponse(CacheStrategy cacheStrategy) {
        }
    });
    try {
        HttpURLConnection connection = new OkUrlFactory(builder.build()).open(url);
        connection.getResponseCode();
    } catch (Exception expected) {
        if (expected.getCause() instanceof URISyntaxException) {
            expected.printStackTrace();
        }
    }
    return uriReference.get();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) CacheRequest(okhttp3.internal.cache.CacheRequest) InternalCache(okhttp3.internal.cache.InternalCache) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) Response(okhttp3.Response) OkUrlFactory(okhttp3.OkUrlFactory) HttpURLConnection(java.net.HttpURLConnection) CacheRequest(okhttp3.internal.cache.CacheRequest) CacheStrategy(okhttp3.internal.cache.CacheStrategy)

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