Search in sources :

Example 11 with Builder

use of okhttp3.OkHttpClient.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.OkHttpClient.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.OkHttpClient.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.OkHttpClient.Builder in project amhttp by Eddieyuan123.

the class RequestBodyFactoryImpl method buildRequestBody.

@Override
public RequestBody buildRequestBody(File file, String fileName, HashMap<String, String> params) {
    MultipartBody.Builder builder = new MultipartBody.Builder();
    if (params == null) {
        throw new NullPointerException("requestBodyFactory build params is null");
    } else {
        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        try {
            if (params.size() > 0) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    builder.addFormDataPart(entry.getKey(), entry.getValue());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        builder.setType(MultipartBody.FORM);
        builder.addFormDataPart("file", fileName, fileBody);
    }
    return builder.build();
}
Also used : MultipartBody(okhttp3.MultipartBody) Map(java.util.Map) HashMap(java.util.HashMap) RequestBody(okhttp3.RequestBody)

Example 15 with Builder

use of okhttp3.OkHttpClient.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)

Aggregations

Request (okhttp3.Request)186 Response (okhttp3.Response)128 OkHttpClient (okhttp3.OkHttpClient)116 IOException (java.io.IOException)97 RequestBody (okhttp3.RequestBody)76 Test (org.junit.Test)68 File (java.io.File)41 MultipartBody (okhttp3.MultipartBody)40 HttpUrl (okhttp3.HttpUrl)39 Map (java.util.Map)34 MockResponse (okhttp3.mockwebserver.MockResponse)32 Call (okhttp3.Call)28 Interceptor (okhttp3.Interceptor)28 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)26 Retrofit (retrofit2.Retrofit)26 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)25 Builder (okhttp3.OkHttpClient.Builder)23 FormBody (okhttp3.FormBody)20 ResponseBody (okhttp3.ResponseBody)20 Builder (okhttp3.Request.Builder)19