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;
}
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;
}
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();
}
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();
}
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();
}
Aggregations