Search in sources :

Example 81 with Builder

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

the class LogInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    Map<String, Object> headers = new HashMap<>();
    Map<String, Object> params = new HashMap<>();
    Map<String, Object> postParm = new HashMap<>();
    //添加公共Header,公共参数
    if (builder != null) {
        headers = builder.getHeaders();
        params = builder.getParams();
        if (!headers.isEmpty()) {
            for (Map.Entry<String, Object> entry : headers.entrySet()) {
                request = request.newBuilder().addHeader(entry.getKey(), String.valueOf(entry.getValue())).build();
            }
        }
        if (!params.isEmpty()) {
            //get请求    添加公共参数
            if (request.method().equals("GET")) {
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    HttpUrl httpUrl = request.url().newBuilder().addQueryParameter(entry.getKey(), String.valueOf(entry.getValue())).build();
                    request = request.newBuilder().url(httpUrl).build();
                }
            }
            if (request.method().equals("POST")) {
                if (request.body() instanceof FormBody) {
                    FormBody.Builder bodyBuilder = new FormBody.Builder();
                    FormBody formBody = (FormBody) request.body();
                    for (int i = 0; i < formBody.size(); i++) {
                        postParm.put(formBody.encodedName(i), formBody.encodedValue(i));
                        bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i));
                    }
                    for (Map.Entry<String, Object> entry : params.entrySet()) {
                        formBody = bodyBuilder.addEncoded(entry.getKey(), String.valueOf(entry.getValue())).build();
                    }
                    request = request.newBuilder().post(formBody).build();
                }
            }
        }
    }
    Response response = chain.proceed(request);
    okhttp3.MediaType mediaType = response.body().contentType();
    String content = response.body().string();
    if (true) {
        OkhttpUtils.println("|---------------日志打印  start---------------------------|");
        OkhttpUtils.println("请求头:" + JSON.toJSONString(response.request().headers().toMultimap()));
        OkhttpUtils.println("url:" + JSON.toJSONString(response.request().url().toString()));
        OkhttpUtils.println("参数:" + JSON.toJSONString(postParm));
        OkhttpUtils.println("结果:" + content);
        OkhttpUtils.println("|---------------日志打印   end---------------------------|");
    }
    return response.newBuilder().body(okhttp3.ResponseBody.create(mediaType, content)).build();
}
Also used : HashMap(java.util.HashMap) Request(okhttp3.Request) FormBody(okhttp3.FormBody) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) Map(java.util.Map) HashMap(java.util.HashMap)

Example 82 with Builder

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

the class OkhttpUtils method sendPostHttp.

/** 
	 * post http
	 * @param url
	 * @param params
	 * @param tag
	 */
public static void sendPostHttp(String url, Map<String, Object> params, String cookies, String tag) {
    Builder paramBuilder = new FormBody.Builder();
    if (!params.isEmpty()) {
        Iterator<Map.Entry<String, Object>> entries = params.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, Object> entry = entries.next();
            paramBuilder.add(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
        }
        OkhttpUtils.println(tag + ":" + url);
        RequestBody formBody = paramBuilder.build();
        Request request = new Request.Builder().url(url).addHeader("content-type", "text/html;charset:utf-8").addHeader("Cookie", cookies).post(formBody).build();
        OkhttpUtils.client.newCall(request).enqueue(new Callback() {

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String requestJson = OkhttpUtils.getResponseString(response);
                RxBus.getInstance().send(tag + ":" + requestJson);
            }

            @Override
            public void onFailure(Call call, IOException e) {
                OkhttpUtils.onFailurePrintln(call, e, this);
            }
        });
    }
}
Also used : Call(okhttp3.Call) Builder(okhttp3.FormBody.Builder) Request(okhttp3.Request) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) Map(java.util.Map) RequestBody(okhttp3.RequestBody)

Example 83 with Builder

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

the class OkhttpUtils method uploadFile.

/**
	 * 多文件+参数 上传功能
	 * @param url
	 * @param params
	 * @param filePaths
	 */
public static void uploadFile(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();
    Request request = new Request.Builder().url(url).post(body).build();
    OkhttpUtils.client.newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            String requestJson = OkhttpUtils.getResponseString(response);
            RxBus.getInstance().send("uploadFile" + ":" + requestJson);
        }

        @Override
        public void onFailure(Call call, IOException e) {
            OkhttpUtils.onFailurePrintln(call, e, this);
        }
    });
}
Also used : Call(okhttp3.Call) Builder(okhttp3.FormBody.Builder) Request(okhttp3.Request) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) MultipartBody(okhttp3.MultipartBody) File(java.io.File) RequestBody(okhttp3.RequestBody)

Example 84 with Builder

use of okhttp3.OkHttpClient.Builder in project Atom_Android by Rogrand-Dev.

the class HttpModule method provideClient.

@Singleton
@Provides
OkHttpClient provideClient(OkHttpClient.Builder builder) {
    if (DemoApp.getAppContext().isDebug()) {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {

            @Override
            public void log(String message) {
                LogUtils.i(TAG, message);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        // 设置 Log 拦截器
        builder.addInterceptor(loggingInterceptor);
    }
    File cacheFile = new File(DataUtils.getCacheFile(DemoApp.getAppContext()), "RograndCache");
    // 100 MB
    int cacheSize = 100 * 1024 * 1024;
    Cache cache = new Cache(cacheFile, cacheSize);
    Interceptor cacheInterceptor = new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            CacheControl.Builder cacheBuilder = new CacheControl.Builder();
            cacheBuilder.maxAge(0, TimeUnit.SECONDS);
            cacheBuilder.maxStale(365, TimeUnit.DAYS);
            CacheControl cacheControl = cacheBuilder.build();
            Request request = chain.request();
            if (!NetUtils.isNetworkAvailable(DemoApp.getAppContext())) {
                request = request.newBuilder().cacheControl(cacheControl).build();
            }
            Response response = chain.proceed(request);
            if (NetUtils.isNetworkAvailable(DemoApp.getAppContext())) {
                // 有网络时, 不缓存, 最大保存时长为0
                int maxAge = 0;
                response.newBuilder().header("Cache-Control", "public, max-age=" + maxAge).removeHeader("Pragma").build();
            } else {
                // 无网络时,设置超时为4周
                int maxStale = 60 * 60 * 24 * 28;
                response.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale).removeHeader("Pragma").build();
            }
            return response;
        }
    };
    // 设置 header(设置 Token、API 版本号)
    Interceptor headerInterceptor = new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            request = request.newBuilder().addHeader("Authorization", "Bearer " + SPUtils.get(DemoApp.getAppContext(), Constants.ACCESS_TOKEN, "")).addHeader("api_version", UrlConstants.API_VERSION).build();
            return chain.proceed(request);
        }
    };
    // 设置统一的请求头部参数
    builder.addInterceptor(headerInterceptor);
    // 设置缓存
    builder.addNetworkInterceptor(cacheInterceptor);
    builder.addInterceptor(cacheInterceptor);
    builder.cache(cache);
    // 设置连接超时
    builder.connectTimeout(TIME_OUT, TimeUnit.SECONDS);
    // 设置读取数据超时
    builder.readTimeout(TIME_OUT, TimeUnit.SECONDS);
    // 设置写入数据超时
    builder.writeTimeout(TIME_OUT, TimeUnit.SECONDS);
    // 设置 Stetho
    builder.addNetworkInterceptor(new StethoInterceptor());
    // 设置 Cookie
    builder.cookieJar(new CookieManger(DemoApp.getAppContext()));
    // 错误重连
    builder.retryOnConnectionFailure(true);
    return builder.build();
}
Also used : CookieManger(com.rogrand.demo.http.cookie.CookieManger) Request(okhttp3.Request) Response(okhttp3.Response) CacheControl(okhttp3.CacheControl) StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) File(java.io.File) StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) Interceptor(okhttp3.Interceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Cache(okhttp3.Cache) Singleton(javax.inject.Singleton) Provides(dagger.Provides)

Example 85 with Builder

use of okhttp3.OkHttpClient.Builder in project Tusky by Vavassor.

the class OkHttpUtils method getCompatibleClientBuilder.

/**
     * Makes a Builder with the maximum range of TLS versions and cipher suites enabled.
     *
     * It first tries the "approved" list of cipher suites given in OkHttp (the default in
     * ConnectionSpec.MODERN_TLS) and if that doesn't work falls back to the set of ALL enabled,
     * then falls back to plain http.
     *
     * API level 24 has a regression in elliptic curves where it only supports secp256r1, so this
     * first tries a fallback without elliptic curves at all, and then tries them after.
     *
     * TLS 1.1 and 1.2 have to be manually enabled on API levels 16-20.
     */
@NonNull
public static OkHttpClient.Builder getCompatibleClientBuilder() {
    ConnectionSpec fallback = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS).allEnabledCipherSuites().supportsTlsExtensions(true).build();
    List<ConnectionSpec> specList = new ArrayList<>();
    specList.add(ConnectionSpec.MODERN_TLS);
    addNougatFixConnectionSpec(specList);
    specList.add(fallback);
    specList.add(ConnectionSpec.CLEARTEXT);
    OkHttpClient.Builder builder = new OkHttpClient.Builder().addInterceptor(getUserAgentInterceptor()).connectionSpecs(specList);
    return enableHigherTlsOnPreLollipop(builder);
}
Also used : OkHttpClient(okhttp3.OkHttpClient) ConnectionSpec(okhttp3.ConnectionSpec) ArrayList(java.util.ArrayList) NonNull(android.support.annotation.NonNull)

Aggregations

Request (okhttp3.Request)42 Response (okhttp3.Response)40 RequestBody (okhttp3.RequestBody)27 OkHttpClient (okhttp3.OkHttpClient)26 IOException (java.io.IOException)25 Test (org.junit.Test)17 Interceptor (okhttp3.Interceptor)9 File (java.io.File)8 URI (java.net.URI)7 X509TrustManager (javax.net.ssl.X509TrustManager)7 MultipartBody (okhttp3.MultipartBody)7 Map (java.util.Map)6 HttpUrl (okhttp3.HttpUrl)6 Provides (dagger.Provides)5 TestClients.clientRequest (keywhiz.TestClients.clientRequest)5 MediaType (okhttp3.MediaType)5 Retrofit (retrofit2.Retrofit)5 SSLContext (javax.net.ssl.SSLContext)4 TrustManager (javax.net.ssl.TrustManager)4 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)4