Search in sources :

Example 41 with Builder

use of okhttp3.Request.Builder in project Fast-Android-Networking by amitshekhariitbhu.

the class InternalNetworking method performSimpleRequest.

public static Response performSimpleRequest(ANRequest request) throws ANError {
    Request okHttpRequest;
    Response okHttpResponse;
    try {
        Request.Builder builder = new Request.Builder().url(request.getUrl());
        addHeadersToRequestBuilder(builder, request);
        RequestBody requestBody = null;
        switch(request.getMethod()) {
            case GET:
                {
                    builder = builder.get();
                    break;
                }
            case POST:
                {
                    requestBody = request.getRequestBody();
                    builder = builder.post(requestBody);
                    break;
                }
            case PUT:
                {
                    requestBody = request.getRequestBody();
                    builder = builder.put(requestBody);
                    break;
                }
            case DELETE:
                {
                    requestBody = request.getRequestBody();
                    builder = builder.delete(requestBody);
                    break;
                }
            case HEAD:
                {
                    builder = builder.head();
                    break;
                }
            case PATCH:
                {
                    requestBody = request.getRequestBody();
                    builder = builder.patch(requestBody);
                    break;
                }
        }
        if (request.getCacheControl() != null) {
            builder.cacheControl(request.getCacheControl());
        }
        okHttpRequest = builder.build();
        if (request.getOkHttpClient() != null) {
            request.setCall(request.getOkHttpClient().newBuilder().cache(sHttpClient.cache()).build().newCall(okHttpRequest));
        } else {
            request.setCall(sHttpClient.newCall(okHttpRequest));
        }
        final long startTime = System.currentTimeMillis();
        final long startBytes = TrafficStats.getTotalRxBytes();
        okHttpResponse = request.getCall().execute();
        final long timeTaken = System.currentTimeMillis() - startTime;
        if (okHttpResponse.cacheResponse() == null) {
            final long finalBytes = TrafficStats.getTotalRxBytes();
            final long diffBytes;
            if (startBytes == TrafficStats.UNSUPPORTED || finalBytes == TrafficStats.UNSUPPORTED) {
                diffBytes = okHttpResponse.body().contentLength();
            } else {
                diffBytes = finalBytes - startBytes;
            }
            ConnectionClassManager.getInstance().updateBandwidth(diffBytes, timeTaken);
            Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, (requestBody != null && requestBody.contentLength() != 0) ? requestBody.contentLength() : -1, okHttpResponse.body().contentLength(), false);
        } else if (request.getAnalyticsListener() != null) {
            if (okHttpResponse.networkResponse() == null) {
                Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, 0, 0, true);
            } else {
                Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, (requestBody != null && requestBody.contentLength() != 0) ? requestBody.contentLength() : -1, 0, true);
            }
        }
    } catch (IOException ioe) {
        throw new ANError(ioe);
    }
    return okHttpResponse;
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) ANRequest(com.androidnetworking.common.ANRequest) IOException(java.io.IOException) ANError(com.androidnetworking.error.ANError) RequestBody(okhttp3.RequestBody)

Example 42 with Builder

use of okhttp3.Request.Builder in project Fast-Android-Networking by amitshekhariitbhu.

the class InternalNetworking method performDownloadRequest.

public static Response performDownloadRequest(final ANRequest request) throws ANError {
    Request okHttpRequest;
    Response okHttpResponse;
    try {
        Request.Builder builder = new Request.Builder().url(request.getUrl());
        addHeadersToRequestBuilder(builder, request);
        builder = builder.get();
        if (request.getCacheControl() != null) {
            builder.cacheControl(request.getCacheControl());
        }
        okHttpRequest = builder.build();
        OkHttpClient okHttpClient;
        if (request.getOkHttpClient() != null) {
            okHttpClient = request.getOkHttpClient().newBuilder().cache(sHttpClient.cache()).addNetworkInterceptor(new Interceptor() {

                @Override
                public Response intercept(Chain chain) throws IOException {
                    Response originalResponse = chain.proceed(chain.request());
                    return originalResponse.newBuilder().body(new ResponseProgressBody(originalResponse.body(), request.getDownloadProgressListener())).build();
                }
            }).build();
        } else {
            okHttpClient = sHttpClient.newBuilder().addNetworkInterceptor(new Interceptor() {

                @Override
                public Response intercept(Chain chain) throws IOException {
                    Response originalResponse = chain.proceed(chain.request());
                    return originalResponse.newBuilder().body(new ResponseProgressBody(originalResponse.body(), request.getDownloadProgressListener())).build();
                }
            }).build();
        }
        request.setCall(okHttpClient.newCall(okHttpRequest));
        final long startTime = System.currentTimeMillis();
        final long startBytes = TrafficStats.getTotalRxBytes();
        okHttpResponse = request.getCall().execute();
        Utils.saveFile(okHttpResponse, request.getDirPath(), request.getFileName());
        final long timeTaken = System.currentTimeMillis() - startTime;
        if (okHttpResponse.cacheResponse() == null) {
            final long finalBytes = TrafficStats.getTotalRxBytes();
            final long diffBytes;
            if (startBytes == TrafficStats.UNSUPPORTED || finalBytes == TrafficStats.UNSUPPORTED) {
                diffBytes = okHttpResponse.body().contentLength();
            } else {
                diffBytes = finalBytes - startBytes;
            }
            ConnectionClassManager.getInstance().updateBandwidth(diffBytes, timeTaken);
            Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, -1, okHttpResponse.body().contentLength(), false);
        } else if (request.getAnalyticsListener() != null) {
            Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, -1, 0, true);
        }
    } catch (IOException ioe) {
        try {
            File destinationFile = new File(request.getDirPath() + File.separator + request.getFileName());
            if (destinationFile.exists()) {
                destinationFile.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new ANError(ioe);
    }
    return okHttpResponse;
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) ANRequest(com.androidnetworking.common.ANRequest) IOException(java.io.IOException) ANError(com.androidnetworking.error.ANError) IOException(java.io.IOException) Response(okhttp3.Response) Interceptor(okhttp3.Interceptor) HttpLoggingInterceptor(com.androidnetworking.interceptors.HttpLoggingInterceptor) File(java.io.File)

Example 43 with Builder

use of okhttp3.Request.Builder in project Fast-Android-Networking by amitshekhariitbhu.

the class ANRequest method getMultiPartRequestBody.

public RequestBody getMultiPartRequestBody() {
    MultipartBody.Builder builder = new MultipartBody.Builder().setType((customMediaType == null) ? MultipartBody.FORM : customMediaType);
    try {
        for (HashMap.Entry<String, String> entry : mMultiPartParameterMap.entrySet()) {
            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\""), RequestBody.create(null, entry.getValue()));
        }
        for (HashMap.Entry<String, File> entry : mMultiPartFileMap.entrySet()) {
            String fileName = entry.getValue().getName();
            RequestBody fileBody = RequestBody.create(MediaType.parse(Utils.getMimeType(fileName)), entry.getValue());
            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\"; filename=\"" + fileName + "\""), fileBody);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return builder.build();
}
Also used : HashMap(java.util.HashMap) MultipartBody(okhttp3.MultipartBody) File(java.io.File) RequestBody(okhttp3.RequestBody)

Example 44 with Builder

use of okhttp3.Request.Builder in project EnableHands by LeviWGG.

the class ServiceFactory method getOkhttpClient.

public OkHttpClient getOkhttpClient() {
    OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
    File cachefile = new File(MyApplication.getMyContext().getExternalCacheDir(), "");
    Cache cache = new Cache(cachefile, 1024 * 1024 * 30);
    builder.cache(cache);
    HttpLogInterceptor httpLogInterceptor = new HttpLogInterceptor();
    builder.addInterceptor(httpLogInterceptor);
    CacheInterceptor cacheInterceptor = new CacheInterceptor();
    builder.addInterceptor(cacheInterceptor);
    builder.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
    builder.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
    builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
    return builder.build();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) HttpLogInterceptor(app.main.wangliwei.enablehands.http.interceptor.HttpLogInterceptor) File(java.io.File) CacheInterceptor(app.main.wangliwei.enablehands.http.interceptor.CacheInterceptor) Cache(okhttp3.Cache)

Example 45 with Builder

use of okhttp3.Request.Builder in project SeeWeather by xcc3641.

the class RetrofitSingleton method initOkHttp.

private static void initOkHttp() {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    // 缓存 http://www.jianshu.com/p/93153b34310e
    File cacheFile = new File(C.NET_CACHE);
    Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
    Interceptor cacheInterceptor = chain -> {
        Request request = chain.request();
        if (!Util.isNetworkConnected(BaseApplication.getAppContext())) {
            request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
        }
        Response response = chain.proceed(request);
        Response.Builder newBuilder = response.newBuilder();
        if (Util.isNetworkConnected(BaseApplication.getAppContext())) {
            int maxAge = 0;
            // 有网络时 设置缓存超时时间0个小时
            newBuilder.header("Cache-Control", "public, max-age=" + maxAge);
        } else {
            // 无网络时,设置超时为4周
            int maxStale = 60 * 60 * 24 * 28;
            newBuilder.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale);
        }
        return newBuilder.build();
    };
    builder.cache(cache).addInterceptor(cacheInterceptor);
    if (BuildConfig.DEBUG) {
        builder.addNetworkInterceptor(new StethoInterceptor());
    }
    // 设置超时
    builder.connectTimeout(15, TimeUnit.SECONDS);
    builder.readTimeout(20, TimeUnit.SECONDS);
    builder.writeTimeout(20, TimeUnit.SECONDS);
    // 错误重连
    builder.retryOnConnectionFailure(true);
    sOkHttpClient = builder.build();
}
Also used : StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) Interceptor(okhttp3.Interceptor) Request(okhttp3.Request) Cache(okhttp3.Cache) BaseApplication(com.xiecc.seeWeather.base.BaseApplication) C(com.xiecc.seeWeather.common.C) CacheControl(okhttp3.CacheControl) Consumer(io.reactivex.functions.Consumer) CityORM(com.xiecc.seeWeather.modules.main.domain.CityORM) File(java.io.File) Retrofit(retrofit2.Retrofit) RxJava2CallAdapterFactory(retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory) BuildConfig(com.xiecc.seeWeather.BuildConfig) TimeUnit(java.util.concurrent.TimeUnit) ToastUtil(com.xiecc.seeWeather.common.utils.ToastUtil) OkHttpClient(okhttp3.OkHttpClient) Util(com.xiecc.seeWeather.common.utils.Util) RxUtil(com.xiecc.seeWeather.common.utils.RxUtil) GsonConverterFactory(retrofit2.converter.gson.GsonConverterFactory) Version(com.xiecc.seeWeather.modules.about.domain.Version) Response(okhttp3.Response) Observable(io.reactivex.Observable) WhereBuilder(com.litesuits.orm.db.assit.WhereBuilder) Weather(com.xiecc.seeWeather.modules.main.domain.Weather) Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) WhereBuilder(com.litesuits.orm.db.assit.WhereBuilder) Request(okhttp3.Request) StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) File(java.io.File) StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) Interceptor(okhttp3.Interceptor) Cache(okhttp3.Cache)

Aggregations

Request (okhttp3.Request)163 Response (okhttp3.Response)120 OkHttpClient (okhttp3.OkHttpClient)91 IOException (java.io.IOException)83 RequestBody (okhttp3.RequestBody)67 Test (org.junit.Test)67 MultipartBody (okhttp3.MultipartBody)35 File (java.io.File)31 Map (java.util.Map)31 MockResponse (okhttp3.mockwebserver.MockResponse)31 HttpUrl (okhttp3.HttpUrl)29 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)27 Call (okhttp3.Call)25 Interceptor (okhttp3.Interceptor)24 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)22 Retrofit (retrofit2.Retrofit)20 Builder (okhttp3.Request.Builder)19 ResponseBody (okhttp3.ResponseBody)18 WatsonServiceUnitTest (com.ibm.watson.developer_cloud.WatsonServiceUnitTest)17 Builder (okhttp3.OkHttpClient.Builder)17