From 560561d22e7be9f93c04c45a873cdee090d62fb0 Mon Sep 17 00:00:00 2001 From: alishatergholi Date: Wed, 20 Feb 2019 14:38:50 +0330 Subject: [PATCH] update gradle extra value update post file add network Interceptor user can check log with details --- app/build.gradle.kts | 16 +- .../com/github/restclient/MainActivity.java | 28 +-- build.gradle.kts | 18 ++ library/build.gradle.kts | 20 +- .../library/ExampleInstrumentedTest.java | 7 +- .../library/Interface/ResultHandler.java | 28 ++- .../java/com/github/library/RestClient.java | 132 +++++++------ .../github/library/enums/RequestBodyType.java | 3 +- .../com/github/library/helper/LogHelper.java | 4 +- .../github/library/requestMethod/DELETE.java | 73 ++----- .../com/github/library/requestMethod/GET.java | 79 +++----- .../github/library/requestMethod/POST.java | 183 +++--------------- .../com/github/library/requestMethod/PUT.java | 115 +++++------ .../library/requestMethod/baseMethod.java | 15 +- .../library/response/ResponseFileHandler.java | 29 +-- .../library/response/ResponseJsonHandler.java | 52 ++--- .../library/response/ResponseTextHandler.java | 29 +-- .../github/library/utils/RequestParams.java | 144 +++++++++----- 18 files changed, 386 insertions(+), 589 deletions(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index b6fcf0e..ab7c149 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -3,13 +3,13 @@ plugins { } android { - compileSdkVersion(28) + compileSdkVersion(rootProject.extra.get("compileSdk") as Int) defaultConfig { - minSdkVersion(15) - targetSdkVersion(28) - buildToolsVersion = "28.0.3" - versionCode = 8 - versionName = "1.0.8" + minSdkVersion(rootProject.extra.get("minSdk") as Int) + targetSdkVersion(rootProject.extra.get("targetSdk") as Int) + buildToolsVersion = rootProject.extra.get("buildTools") as String + versionCode = rootProject.extra.get("version_code") as Int + versionName = rootProject.extra.get("version_name") as String testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } buildTypes { @@ -27,9 +27,9 @@ android { dependencies { implementation(fileTree(mapOf("include" to listOf("*.jar"), "dir" to "libs"))) implementation("androidx.appcompat:appcompat:1.0.2") - implementation("com.github.alishatergholi:rest-client:v1.0.9") + //implementation("com.github.alishatergholi:rest-client:v1.0.9") testImplementation("junit:junit:4.12") -// implementation(project(":library")) + implementation(project(":library")) androidTestImplementation("androidx.test:runner:1.1.1") androidTestImplementation("androidx.test.espresso:espresso-core:3.1.1") } diff --git a/app/src/main/java/com/github/restclient/MainActivity.java b/app/src/main/java/com/github/restclient/MainActivity.java index b0ee86b..95ec6d1 100644 --- a/app/src/main/java/com/github/restclient/MainActivity.java +++ b/app/src/main/java/com/github/restclient/MainActivity.java @@ -2,22 +2,18 @@ import android.os.Bundle; +import android.os.StrictMode; import android.util.Log; -import org.json.JSONArray; -import org.json.JSONObject; - -import androidx.appcompat.app.AppCompatActivity; -import androidx.collection.ArrayMap; - import com.github.library.RestClient; - import com.github.library.enums.AuthType; - import com.github.library.enums.RequestBodyType; import com.github.library.response.ResponseJsonHandler; import com.github.library.utils.RequestParams; +import androidx.appcompat.app.AppCompatActivity; +import androidx.collection.ArrayMap; + public class MainActivity extends AppCompatActivity { @@ -34,25 +30,19 @@ protected void onCreate(Bundle savedInstanceState) { findViewById(R.id.text).setOnClickListener(view -> { RequestParams params = new RequestParams(RequestBodyType.FormData); - params.put("page", "1"); - - - restClient.POST("https://google.com", + restClient.POST("https://sandbox.vaslapp.com", "", new RequestParams(), new ResponseJsonHandler() { - @Override protected void onSuccess(String result) { Log.d(TAG, "response " + result); } - @Override public void onFailure(int errorCode, String errorMsg) { Log.d(TAG, "onFailure " + errorMsg); } - } - ); + }); }); } @@ -62,8 +52,10 @@ private void initRestClient() { header.put("accept-language", "en"); restClient = new RestClient.Builder(this) - .setAuthorization("http://sandbox.vaslapp.com/oauth/token", - "c3bdf6c5-508f-48ae-9af4-243a24072e31", "LnDbEo3yDDcswKMC3h4H", AuthType.BASIC_AUTH) + .setAuthorization("https://sandbox.vaslapp.com/oauth/token", + "c3bdf6c5-508f-48ae-9af4-243a24072e31", + "LnDbEo3yDDcswKMC3h4H", + AuthType.BASIC_AUTH) .setUserInfo("android-XoaM8ODAYVcKnB16ob8N", "DOI0qOIa0KT6ViYmS1k6") .setHeader(header) .build(); diff --git a/build.gradle.kts b/build.gradle.kts index 362b1f1..34a1774 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,5 +1,14 @@ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { + + extra.set("kotlinVersion" , "1.3.20") + extra.set("minSdk" , 15) + extra.set("compileSdk" , 28) + extra.set("targetSdk" , 28) + extra.set("buildTools" , "28.0.3") + extra.set("version_code" , 10) + extra.set("version_name" , "1.1.0") + repositories { google() jcenter() @@ -11,8 +20,16 @@ buildscript { // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } + // Define versions in a single place + extra.apply{ + set("minSdkVersion", 26) + set("targetSdkVersion", 27) + } + } + + allprojects { repositories { google() @@ -20,6 +37,7 @@ allprojects { maven("https://jitpack.io") } + } task("clean") { diff --git a/library/build.gradle.kts b/library/build.gradle.kts index 4078f0b..0f51075 100644 --- a/library/build.gradle.kts +++ b/library/build.gradle.kts @@ -4,16 +4,16 @@ plugins { } group = "com.github.rest-client" -version = "1.0.9" +version = rootProject.extra.get("version_name")!! android { - compileSdkVersion(28) + compileSdkVersion(rootProject.extra.get("compileSdk") as Int) defaultConfig { - minSdkVersion(15) - targetSdkVersion(28) - buildToolsVersion = "28.0.3" - versionCode = 9 - versionName = "1.0.9" + minSdkVersion(rootProject.extra.get("minSdk") as Int) + targetSdkVersion(rootProject.extra.get("targetSdk") as Int) + buildToolsVersion = rootProject.extra.get("buildTools") as String + versionCode = rootProject.extra.get("version_code") as Int + versionName = rootProject.extra.get("version_name") as String testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } buildTypes { @@ -30,15 +30,19 @@ android { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } + + } dependencies { + implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar")))) - implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.20") + implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7:${rootProject.extra.get("kotlinVersion")}") implementation("androidx.appcompat:appcompat:1.0.2") implementation("com.squareup.okhttp3:okhttp:3.12.0") //implementation("androidx.annotation:annotation:1.0.1") testImplementation("junit:junit:4.12") androidTestImplementation("androidx.test:runner:1.1.1") androidTestImplementation("androidx.test.espresso:espresso-core:3.1.1") + } diff --git a/library/src/androidTest/java/com/github/library/ExampleInstrumentedTest.java b/library/src/androidTest/java/com/github/library/ExampleInstrumentedTest.java index b51f1c0..cb22283 100644 --- a/library/src/androidTest/java/com/github/library/ExampleInstrumentedTest.java +++ b/library/src/androidTest/java/com/github/library/ExampleInstrumentedTest.java @@ -1,13 +1,14 @@ package com.github.library; import android.content.Context; -import android.support.test.InstrumentationRegistry; -import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; -import static org.junit.Assert.*; +import androidx.test.InstrumentationRegistry; +import androidx.test.runner.AndroidJUnit4; + +import static org.junit.Assert.assertEquals; /** * Instrumented test, which will execute on an Android device. diff --git a/library/src/main/java/com/github/library/Interface/ResultHandler.java b/library/src/main/java/com/github/library/Interface/ResultHandler.java index e14db6a..e210c8d 100644 --- a/library/src/main/java/com/github/library/Interface/ResultHandler.java +++ b/library/src/main/java/com/github/library/Interface/ResultHandler.java @@ -3,16 +3,14 @@ +import com.github.library.enums.ErrorCode; + import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.TimeUnit; import java.util.zip.GZIPInputStream; - -import com.github.library.enums.ErrorCode; -import com.github.library.helper.LogHelper; - import okhttp3.Response; import okhttp3.ResponseBody; @@ -22,11 +20,9 @@ */ public abstract class ResultHandler { - protected LogHelper logHelper = new LogHelper(ResultHandler.class); - - public void onResultHandler(long startTime,Response response){ + public void onResultHandler(Response response){ String url = response.request().url().url().toString(); - if (response.body() != null && response.body().source() != null && response.isSuccessful()) { + if (response.body() != null && response.isSuccessful()) { InputStream inputStream = null; String contentEncodingHeader = response.header("Content-Encoding"); ResponseBody body = response.body(); @@ -35,7 +31,7 @@ public void onResultHandler(long startTime,Response response){ try { inputStream = new GZIPInputStream(body.byteStream()); } catch (IOException e) { - this.onFailure(url,startTime,ErrorCode.IOException); + this.onFailure(url,ErrorCode.IOException); } } else { inputStream = body.byteStream(); @@ -51,28 +47,28 @@ public void onResultHandler(long startTime,Response response){ outputStream.flush(); byte[] result = outputStream.toByteArray(); outputStream.close(); - this.onSuccess(url,startTime,result); + this.onSuccess(url,result); } catch (IOException e) { - this.onFailure(url,startTime,ErrorCode.IOException); + this.onFailure(url,ErrorCode.IOException); } }else { - this.onFailure(url,startTime,ErrorCode.ParseException); + this.onFailure(url,ErrorCode.ParseException); } } else { - this.onFailure(url,startTime,ErrorCode.NullPointerException); + this.onFailure(url,ErrorCode.NullPointerException); } } else { - this.onFailure(url,startTime,ErrorCode.Parse(response.code())); + this.onFailure(url,ErrorCode.Parse(response.code())); } } - protected abstract void onSuccess(String url,long startTime,byte[] result); + protected abstract void onSuccess(String url,byte[] result); public void onProgress(double percent,long bytesWritten,long totalSize){ } - public abstract void onFailure(String url,long startTime,ErrorCode errorCode); + public abstract void onFailure(String url,ErrorCode errorCode); protected static String calcTime(Long startTime) { Long duration = getTimeMillisecond() - startTime; diff --git a/library/src/main/java/com/github/library/RestClient.java b/library/src/main/java/com/github/library/RestClient.java index 1214476..c0b886f 100644 --- a/library/src/main/java/com/github/library/RestClient.java +++ b/library/src/main/java/com/github/library/RestClient.java @@ -1,33 +1,36 @@ +/** + * Created by alishatergholi on 2/20/18. + */ package com.github.library; - import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; - -import java.util.concurrent.TimeUnit; - - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.collection.ArrayMap; import com.github.library.Interface.ResultHandler; import com.github.library.enums.AuthType; import com.github.library.enums.EncodingType; import com.github.library.enums.ErrorCode; +import com.github.library.helper.LogHelper; import com.github.library.model.AuthModel; import com.github.library.requestMethod.DELETE; import com.github.library.requestMethod.GET; import com.github.library.requestMethod.POST; import com.github.library.requestMethod.PUT; import com.github.library.utils.RequestParams; + +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +import androidx.collection.ArrayMap; import okhttp3.Call; +import okhttp3.Interceptor; import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; -/** - * Created by alishatergholi on 2/20/18. - */ public class RestClient { private static OkHttpClient instance; @@ -38,11 +41,18 @@ private static synchronized OkHttpClient getClient() { .newBuilder() .connectTimeout(30, TimeUnit.SECONDS) .build(); + + if (debugEnable) { + instance.newBuilder() + .addInterceptor(new LoggingInterceptor()) + .build(); + } } return instance; } private Context appContext; + private String clientId; private String clientSecret; private String site; @@ -53,11 +63,13 @@ private static synchronized OkHttpClient getClient() { private String username; private String password; + private static boolean debugEnable = true; + private AuthType authType; private EncodingType encodingType; private ArrayMap headers; - RestClient(Builder builder){ + public RestClient(Builder builder){ this.appContext = builder.appContext; this.clientId = builder.clientId; this.clientSecret = builder.clientSecret; @@ -66,6 +78,7 @@ private static synchronized OkHttpClient getClient() { this.grantType = builder.grantType; this.username = builder.username; this.password = builder.password; + this.debugEnable = builder.debugEnable; this.authType = builder.authType; this.encodingType = builder.encodingType; this.headers = builder.headers; @@ -85,6 +98,8 @@ public static class Builder { private String username; private String password; + private boolean debugEnable = true; + private AuthType authType = AuthType.NO_AUTH; private EncodingType encodingType = EncodingType.NO_ENCODING; private ArrayMap headers = new ArrayMap<>(); @@ -127,11 +142,33 @@ public Builder setHeader(ArrayMap headers){ return this; } + public Builder setDebugEnable(boolean enable){ + this.debugEnable = enable; + return this; + } + public RestClient build() { return new RestClient(this); } } + private static class LoggingInterceptor implements Interceptor { + + LogHelper logHelper = new LogHelper(RestClient.class); + + @NotNull + @Override + public Response intercept(@NotNull Interceptor.Chain chain) throws IOException { + Request request = chain.request(); + long t1 = System.nanoTime(); + logHelper.d(String.format("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers())); + Response response = chain.proceed(request); + long t2 = System.nanoTime(); + logHelper.d(String.format("Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers())); + return response; + } + } + private static boolean checkNetworkConnection(Context context) { try { if (context == null) { @@ -149,13 +186,13 @@ private static boolean checkNetworkConnection(Context context) { } public void POST( - @NonNull final String url, - @Nullable final String tag, - @NonNull final RequestParams params, - @NonNull final ResultHandler responder){ + String url, + String tag, + RequestParams params, + ResultHandler responder){ if (checkNetworkConnection(this.appContext)) { - responder.onFailure(url,0,ErrorCode.InternetConnectionError); + responder.onFailure(url,ErrorCode.InternetConnectionError); return; } //region Authorization Model @@ -181,46 +218,13 @@ public void POST( } } - public void POST_FILE( - @NonNull final String url, - @Nullable final String tag, - @NonNull final RequestParams params, - @NonNull final ResultHandler responder){ - - if (checkNetworkConnection(this.appContext)) { - responder.onFailure(url,0,ErrorCode.InternetConnectionError); - return; - } - //region Authorization Model - AuthModel auth = new AuthModel(); - auth.setClientId(this.clientId); - auth.setClientSecret(this.clientSecret); - auth.setSite(this.site); - auth.setScope(this.scope); - auth.setGrantType(this.grantType); - auth.setUsername(this.username); - auth.setPassword(this.password); - auth.setAuthType(this.authType); - auth.setEncodingType(this.encodingType); - auth.setHeaders(this.headers); - //endregion - switch (this.authType){ - case NO_AUTH: - POST.file_no_Auth(getClient(), url, tag, auth, params, responder); - break; - case BASIC_AUTH: - POST.file_basic_Auth(getClient(),url,tag,auth,params,responder); - break; - } - } - public void GET( - @NonNull final String url, - @Nullable final String tag, - @NonNull final ResultHandler responder){ + String url, + String tag, + ResultHandler responder){ if (checkNetworkConnection(this.appContext)) { - responder.onFailure(url,0,ErrorCode.InternetConnectionError); + responder.onFailure(url,ErrorCode.InternetConnectionError); return; } //region Authorization Model @@ -247,13 +251,13 @@ public void GET( } public void DELETE( - @NonNull final String url, - @Nullable final String tag, - @NonNull final RequestParams params, - @NonNull final ResultHandler responder){ + String url, + String tag, + RequestParams params, + ResultHandler responder){ if (checkNetworkConnection(this.appContext)) { - responder.onFailure(url,0,ErrorCode.InternetConnectionError); + responder.onFailure(url,ErrorCode.InternetConnectionError); return; } //region Authorization Model @@ -280,13 +284,13 @@ public void DELETE( } public void PUT( - @NonNull final String url, - @Nullable final String tag, - @NonNull final RequestParams params, - @NonNull final ResultHandler responder){ + String url, + String tag, + RequestParams params, + ResultHandler responder){ if (checkNetworkConnection(this.appContext)) { - responder.onFailure(url,0,ErrorCode.InternetConnectionError); + responder.onFailure(url,ErrorCode.InternetConnectionError); return; } //region Authorization Model diff --git a/library/src/main/java/com/github/library/enums/RequestBodyType.java b/library/src/main/java/com/github/library/enums/RequestBodyType.java index 8210321..14ade3a 100644 --- a/library/src/main/java/com/github/library/enums/RequestBodyType.java +++ b/library/src/main/java/com/github/library/enums/RequestBodyType.java @@ -8,7 +8,8 @@ public enum RequestBodyType { FormUrlEncode(1), RawJSON(2), RawTEXTPlain(3), - Binary(4),; + Binary(4), + MultiPart(5); int value = -1; diff --git a/library/src/main/java/com/github/library/helper/LogHelper.java b/library/src/main/java/com/github/library/helper/LogHelper.java index 250ba9b..779660d 100644 --- a/library/src/main/java/com/github/library/helper/LogHelper.java +++ b/library/src/main/java/com/github/library/helper/LogHelper.java @@ -3,11 +3,13 @@ import android.util.Log; import com.github.library.BuildConfig; +import com.github.library.RestClient; public class LogHelper { - private String LOG_TAG = "Restful"; + private String LOG_TAG = "Rest-Client"; + private static final int MAX_LOG_TAG_LENGTH = 23; diff --git a/library/src/main/java/com/github/library/requestMethod/DELETE.java b/library/src/main/java/com/github/library/requestMethod/DELETE.java index 7331d98..09b6932 100644 --- a/library/src/main/java/com/github/library/requestMethod/DELETE.java +++ b/library/src/main/java/com/github/library/requestMethod/DELETE.java @@ -3,21 +3,20 @@ import android.os.Handler; import android.os.Looper; -import java.io.IOException; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.collection.ArrayMap; -import com.github.library.Interface.OAuthResponseCallback; import com.github.library.Interface.ResultHandler; import com.github.library.enums.ErrorCode; import com.github.library.helper.general; import com.github.library.model.AuthModel; -import com.github.library.model.OAuthResponse; import com.github.library.oauth2.OAuth2Client; import com.github.library.response.ResponseJsonHandler; import com.github.library.response.ResponseTextHandler; import com.github.library.utils.RequestParams; + +import java.io.IOException; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.collection.ArrayMap; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; @@ -33,7 +32,6 @@ public synchronized static void no_Auth( @NonNull final AuthModel authModel, @NonNull final RequestParams params, @NonNull final ResultHandler responder) { - final Long startTime = getTimeMillisecond(); try { final Request.Builder request = new Request.Builder() .url(url) @@ -68,37 +66,22 @@ public synchronized static void no_Auth( } } } catch (Exception e) { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - responder.onFailure(url,startTime,ErrorCode.RuntimeException); - } - }); + new Handler(Looper.getMainLooper()).post(() -> responder.onFailure(url,ErrorCode.RuntimeException)); } } client.newCall(request.build()).enqueue(new Callback() { @Override public void onFailure(@NonNull Call call, final IOException e) { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - responder.onFailure(url,startTime,ErrorCode.ServerConnectionError); - } - }); + new Handler(Looper.getMainLooper()).post(() -> responder.onFailure(url,ErrorCode.ServerConnectionError)); } @Override public void onResponse(@NonNull Call call, @NonNull final Response response) { - responder.onResultHandler(startTime,response); + responder.onResultHandler(response); } }); } catch (Exception ex) { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - responder.onFailure(url,startTime,ErrorCode.RuntimeException); - } - }); + new Handler(Looper.getMainLooper()).post(() -> responder.onFailure(url,ErrorCode.RuntimeException)); } } @@ -109,38 +92,24 @@ public synchronized static void basic_Auth( @NonNull final AuthModel authModel, @NonNull final RequestParams params, @NonNull final ResultHandler responder) { - final Long startTime = getTimeMillisecond(); try { final ArrayMap headers = authModel.getHeaders(); OAuth2Client auth = new OAuth2Client(client,headers,authModel); - auth.requestAccessToken(new OAuthResponseCallback() { - @Override - public void onResponse(OAuthResponse response) { - if (response.isSuccessful()) { - switch (authModel.getAuthType()){ - case BASIC_AUTH: - headers.put("Authorization", String.format("Bearer %s", response.getAccessToken())); - break; - } - authModel.setHeaders(headers); - no_Auth(client,url,tag,authModel,params,responder); - } else { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - responder.onFailure(url,startTime,ErrorCode.AuthorizationException); - } - }); + auth.requestAccessToken(response -> { + if (response.isSuccessful()) { + switch (authModel.getAuthType()){ + case BASIC_AUTH: + headers.put("Authorization", String.format("Bearer %s", response.getAccessToken())); + break; } + authModel.setHeaders(headers); + no_Auth(client,url,tag,authModel,params,responder); + } else { + new Handler(Looper.getMainLooper()).post(() -> responder.onFailure(url,ErrorCode.AuthorizationException)); } }); } catch (Exception ex) { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - responder.onFailure(url,startTime,ErrorCode.RuntimeException); - } - }); + new Handler(Looper.getMainLooper()).post(() -> responder.onFailure(url,ErrorCode.RuntimeException)); } } } diff --git a/library/src/main/java/com/github/library/requestMethod/GET.java b/library/src/main/java/com/github/library/requestMethod/GET.java index 8007fdd..be649c2 100644 --- a/library/src/main/java/com/github/library/requestMethod/GET.java +++ b/library/src/main/java/com/github/library/requestMethod/GET.java @@ -3,20 +3,21 @@ import android.os.Handler; import android.os.Looper; -import java.io.IOException; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.collection.ArrayMap; -import com.github.library.Interface.OAuthResponseCallback; import com.github.library.Interface.ResultHandler; import com.github.library.enums.ErrorCode; import com.github.library.helper.general; import com.github.library.model.AuthModel; -import com.github.library.model.OAuthResponse; import com.github.library.oauth2.OAuth2Client; import com.github.library.response.ResponseJsonHandler; import com.github.library.response.ResponseTextHandler; + +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.collection.ArrayMap; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; @@ -31,7 +32,6 @@ public synchronized static void no_Auth( @Nullable String tag, @NonNull AuthModel authModel, @NonNull final ResultHandler responder) { - final Long startTime = getTimeMillisecond(); try { final Request.Builder request = new Request.Builder() .url(url) @@ -66,37 +66,22 @@ public synchronized static void no_Auth( } } } catch (Exception e) { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - responder.onFailure(url,startTime,ErrorCode.RuntimeException); - } - }); + new Handler(Looper.getMainLooper()).post(() -> responder.onFailure(url,ErrorCode.RuntimeException)); } } client.newCall(request.build()).enqueue(new Callback() { @Override - public void onFailure(@NonNull Call call, IOException e) { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - responder.onFailure(url,startTime,ErrorCode.ServerConnectionError); - } - }); + public void onFailure(@NonNull Call call, @NotNull IOException e) { + new Handler(Looper.getMainLooper()).post(() -> responder.onFailure(url,ErrorCode.ServerConnectionError)); } @Override - public void onResponse(@NonNull Call call, @NonNull final Response response) { - responder.onResultHandler(startTime,response); + public void onResponse(@NonNull Call call, @NonNull Response response) { + responder.onResultHandler(response); } }); } catch (Exception ex) { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - responder.onFailure(url,startTime,ErrorCode.RuntimeException); - } - }); + new Handler(Looper.getMainLooper()).post(() -> responder.onFailure(url,ErrorCode.RuntimeException)); } } @@ -106,38 +91,24 @@ public synchronized static void basic_Auth( @Nullable final String tag, @NonNull final AuthModel authModel, @NonNull final ResultHandler responder) { - final Long startTime = getTimeMillisecond(); try { final ArrayMap headers = authModel.getHeaders(); OAuth2Client auth = new OAuth2Client(client,headers,authModel); - auth.requestAccessToken(new OAuthResponseCallback() { - @Override - public void onResponse(OAuthResponse response) { - if (response.isSuccessful()) { - switch (authModel.getAuthType()){ - case BASIC_AUTH: - headers.put("Authorization", String.format("Bearer %s", response.getAccessToken())); - break; - } - authModel.setHeaders(headers); - no_Auth(client,url,tag,authModel,responder); - } else { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - responder.onFailure(url,startTime,ErrorCode.AuthorizationException); - } - }); + auth.requestAccessToken(response -> { + if (response.isSuccessful()) { + switch (authModel.getAuthType()){ + case BASIC_AUTH: + headers.put("Authorization", String.format("Bearer %s", response.getAccessToken())); + break; } + authModel.setHeaders(headers); + no_Auth(client,url,tag,authModel,responder); + } else { + new Handler(Looper.getMainLooper()).post(() -> responder.onFailure(url,ErrorCode.AuthorizationException)); } }); } catch (Exception ex) { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - responder.onFailure(url,startTime,ErrorCode.RuntimeException); - } - }); + new Handler(Looper.getMainLooper()).post(() -> responder.onFailure(url,ErrorCode.RuntimeException)); } } diff --git a/library/src/main/java/com/github/library/requestMethod/POST.java b/library/src/main/java/com/github/library/requestMethod/POST.java index 2acddc7..224712a 100644 --- a/library/src/main/java/com/github/library/requestMethod/POST.java +++ b/library/src/main/java/com/github/library/requestMethod/POST.java @@ -3,57 +3,65 @@ import android.os.Handler; import android.os.Looper; -import com.github.library.Interface.OAuthResponseCallback; import com.github.library.Interface.ResultHandler; import com.github.library.enums.ErrorCode; +import com.github.library.enums.RequestBodyType; import com.github.library.helper.general; import com.github.library.model.AuthModel; -import com.github.library.model.FileModel; -import com.github.library.model.OAuthResponse; import com.github.library.oauth2.OAuth2Client; import com.github.library.response.ResponseJsonHandler; import com.github.library.response.ResponseTextHandler; import com.github.library.utils.RequestBodyProgressive; import com.github.library.utils.RequestParams; +import org.jetbrains.annotations.NotNull; + import java.io.IOException; -import java.util.LinkedHashMap; -import java.util.Objects; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.collection.ArrayMap; import okhttp3.Call; import okhttp3.Callback; -import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; -import okhttp3.ResponseBody; public class POST extends baseMethod { public synchronized static void no_Auth( @NonNull OkHttpClient client, - @NonNull final String url, + @NonNull String url, @Nullable String tag, @NonNull AuthModel authModel, @NonNull RequestParams params, - @NonNull final ResultHandler responder) { - final Long startTime = getTimeMillisecond(); + @NonNull ResultHandler responder) { try { + RequestBody requestBody; + if (params.getType() == RequestBodyType.MultiPart) + requestBody = new RequestBodyProgressive(params.getRequestForm(), (bytesWritten, contentLength) -> + new Handler(Looper.getMainLooper()).post(() -> { + double percent = (double) bytesWritten / (double) contentLength; + percent = Math.floor(percent * 100) / 1; + responder.onProgress(percent, bytesWritten, contentLength); + })); + else { + requestBody = params.getRequestForm(); + } Request.Builder request = new Request.Builder() .url(url) .tag(tag) .addHeader("cache-control", "no-cache") .addHeader("os", "android") - .post(params.getRequestForm()); + .post(requestBody); + switch (authModel.getEncodingType()) { case GZIP: request.addHeader("Accept-Encoding", "gzip"); break; } + if (responder instanceof ResponseTextHandler) { request.addHeader("Content-Type", "application/text"); request.addHeader("Accept", "application/text"); @@ -64,6 +72,7 @@ public synchronized static void no_Auth( request.addHeader("Content-Type", "application/x-www-form-urlencoded"); request.addHeader("Accept", "application/octet-stream"); } + ArrayMap headers = authModel.getHeaders(); for (int index = 0; index < headers.size(); index++) { try { @@ -75,159 +84,32 @@ public synchronized static void no_Auth( } } } catch (Exception e) { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - responder.onFailure(url, startTime, ErrorCode.RuntimeException); - } - }); + new Handler(Looper.getMainLooper()).post(() -> responder.onFailure(url, ErrorCode.RuntimeException)); } } client.newCall(request.build()).enqueue(new Callback() { @Override - public void onFailure(@NonNull Call call, final IOException e) { - responder.onFailure(url, startTime, ErrorCode.ServerConnectionError); + public void onFailure(@NonNull Call call, @NotNull IOException e) { + responder.onFailure(url, ErrorCode.ServerConnectionError); } @Override public void onResponse(@NonNull Call call, @NonNull final Response response) { - responder.onResultHandler(startTime, response); + responder.onResultHandler(response); } }); } catch (Exception ex) { - responder.onFailure(url, startTime, ErrorCode.RuntimeException); + responder.onFailure(url, ErrorCode.RuntimeException); } } public synchronized static void basic_Auth( - @NonNull final OkHttpClient client, - @NonNull final String url, - @Nullable final String tag, - @NonNull final AuthModel authModel, - @NonNull final RequestParams params, - @NonNull final ResultHandler responder) { - final Long startTime = getTimeMillisecond(); - try { - final ArrayMap headers = authModel.getHeaders(); - OAuth2Client auth = new OAuth2Client(client, headers, authModel); - auth.requestAccessToken(new OAuthResponseCallback() { - @Override - public void onResponse(OAuthResponse response) { - if (response.isSuccessful()) { - switch (authModel.getAuthType()) { - case BASIC_AUTH: - headers.put("Authorization", String.format("Bearer %s", response.getAccessToken())); - break; - } - authModel.setHeaders(headers); - no_Auth(client, url, tag, authModel, params, responder); - } else { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - responder.onFailure(url, startTime, ErrorCode.AuthorizationException); - } - }); - } - } - }); - } catch (Exception ex) { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - responder.onFailure(url, startTime, ErrorCode.RuntimeException); - } - }); - } - } - -// static class LoggingInterceptor implements Interceptor { -// @Override public Response intercept(Interceptor.Chain chain) throws IOException { -// Request request = chain.request(); -// long t1 = System.nanoTime(); -// logger.d(String.format("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers())); -// Response response = chain.proceed(request); -// long t2 = System.nanoTime(); -// logger.d(String.format("Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers())); -// return response; -// } -// } - - public synchronized static void file_no_Auth( @NonNull OkHttpClient client, - @NonNull final String url, + @NonNull String url, @Nullable String tag, @NonNull AuthModel authModel, @NonNull RequestParams params, - @NonNull final ResultHandler responder) { - final Long startTime = getTimeMillisecond(); - try { - MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM); - LinkedHashMap parameters = params.getParams(); - for (String key : parameters.keySet()) { - builder.addFormDataPart(key, (String) Objects.requireNonNull(parameters.get(key))); - } - LinkedHashMap fileParams = params.getFileParams(); - for (String key : fileParams.keySet()) { - FileModel uploadFile = fileParams.get(key); - if (uploadFile != null) { - builder.addFormDataPart(key, uploadFile.getFilenName(), RequestBody.create(uploadFile.getMimeType(), uploadFile.getFile())); - } - } - RequestBodyProgressive progressiveBuilder = new RequestBodyProgressive(builder.build(), (bytesWritten, contentLength) -> { - new Handler(Looper.getMainLooper()).post(() -> { - Double percent = (double) bytesWritten / (double) contentLength; - percent = Math.floor(percent * 100) / 1; - responder.onProgress(percent,(long) bytesWritten,(long)contentLength); - }); - }); - Request.Builder request = new Request.Builder() - .url(url) - .addHeader("accept-language" , "fa") - .addHeader("cache-control" , "no-cache") - .addHeader("os" , "android") - .post(progressiveBuilder); - switch (authModel.getEncodingType()) { - case GZIP: - request.addHeader("Accept-Encoding", "gzip"); - break; - } - - if (responder instanceof ResponseTextHandler) { - request.addHeader("Content-Type", "application/text"); - request.addHeader("Accept", "application/text"); - } else if (responder instanceof ResponseJsonHandler) { - request.addHeader("Content-Type", "application/json; charset=utf-8"); - request.addHeader("Accept", "application/json"); - } else { - request.addHeader("Content-Type", "application/x-www-form-urlencoded"); - request.addHeader("Accept", "application/octet-stream"); - } - - client.newCall(request.build()).enqueue(new Callback() { - @Override - public void onFailure(@NonNull Call call, @NonNull IOException e) { - new Handler(Looper.getMainLooper()).post(() -> responder.onFailure(url,startTime,ErrorCode.ServerConnectionError)); - } - - @Override - public void onResponse(@NonNull Call call, @NonNull Response response) { - responder.onResultHandler(startTime,response); - } - }); - } catch (Exception e) { - new Handler(Looper.getMainLooper()).post(() -> responder.onFailure(url,startTime,ErrorCode.Exception)); - } - } - - public synchronized static void file_basic_Auth( - @NonNull final OkHttpClient client, - @NonNull final String url, - @Nullable final String tag, - @NonNull final AuthModel authModel, - @NonNull final RequestParams params, - @NonNull final ResultHandler responder) { - final Long startTime = getTimeMillisecond(); + @NonNull ResultHandler responder) { try { final ArrayMap headers = authModel.getHeaders(); OAuth2Client auth = new OAuth2Client(client, headers, authModel); @@ -239,18 +121,13 @@ public synchronized static void file_basic_Auth( break; } authModel.setHeaders(headers); - file_no_Auth(client, url, tag, authModel, params, responder); + no_Auth(client, url, tag, authModel, params, responder); } else { - new Handler(Looper.getMainLooper()).post(() -> { - responder.onFailure(url, startTime, ErrorCode.AuthorizationException); - }); + new Handler(Looper.getMainLooper()).post(() -> responder.onFailure(url, ErrorCode.AuthorizationException)); } }); } catch (Exception ex) { - new Handler(Looper.getMainLooper()).post(() -> { - responder.onFailure(url, startTime, ErrorCode.RuntimeException); - }); + new Handler(Looper.getMainLooper()).post(() -> responder.onFailure(url, ErrorCode.RuntimeException)); } } - } diff --git a/library/src/main/java/com/github/library/requestMethod/PUT.java b/library/src/main/java/com/github/library/requestMethod/PUT.java index ce30f79..c16be8c 100644 --- a/library/src/main/java/com/github/library/requestMethod/PUT.java +++ b/library/src/main/java/com/github/library/requestMethod/PUT.java @@ -3,25 +3,29 @@ import android.os.Handler; import android.os.Looper; -import java.io.IOException; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.collection.ArrayMap; -import com.github.library.Interface.OAuthResponseCallback; import com.github.library.Interface.ResultHandler; import com.github.library.enums.ErrorCode; +import com.github.library.enums.RequestBodyType; import com.github.library.helper.general; import com.github.library.model.AuthModel; -import com.github.library.model.OAuthResponse; import com.github.library.oauth2.OAuth2Client; import com.github.library.response.ResponseJsonHandler; import com.github.library.response.ResponseTextHandler; +import com.github.library.utils.RequestBodyProgressive; import com.github.library.utils.RequestParams; + +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.collection.ArrayMap; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; +import okhttp3.RequestBody; import okhttp3.Response; public class PUT extends baseMethod { @@ -33,34 +37,44 @@ public synchronized static void no_Auth( @NonNull AuthModel authModel, @NonNull RequestParams params, @NonNull final ResultHandler responder) { - final Long startTime = getTimeMillisecond(); try { - final Request.Builder request = new Request.Builder() + RequestBody requestBody; + if (params.getType() == RequestBodyType.MultiPart) { + requestBody = new RequestBodyProgressive(params.getRequestForm(), (bytesWritten, contentLength) -> + new Handler(Looper.getMainLooper()).post(() -> { + double percent = (double) bytesWritten / (double) contentLength; + percent = Math.floor(percent * 100) / 1; + responder.onProgress(percent, bytesWritten, contentLength); + })); + } else { + requestBody = params.getRequestForm(); + } + Request.Builder request = new Request.Builder() .url(url) .tag(tag) - .addHeader("cache-control" , "no-cache") - .addHeader("os" , "android") - .put(params.getRequestForm()); + .addHeader("cache-control", "no-cache") + .addHeader("os", "android") + .put(requestBody); - switch (authModel.getEncodingType()){ + switch (authModel.getEncodingType()) { case GZIP: - request.addHeader("Accept-Encoding","gzip"); + request.addHeader("Accept-Encoding", "gzip"); break; } - if (responder instanceof ResponseTextHandler){ + if (responder instanceof ResponseTextHandler) { request.addHeader("Content-Type", "application/text"); request.addHeader("Accept", "application/text"); - }else if (responder instanceof ResponseJsonHandler){ + } else if (responder instanceof ResponseJsonHandler) { request.addHeader("Content-Type", "application/json"); request.addHeader("Accept", "application/json"); - }else { + } else { request.addHeader("Content-Type", "application/x-www-form-urlencoded"); request.addHeader("Accept", "application/octet-stream"); } ArrayMap headers = authModel.getHeaders(); - for (int index = 0;index < headers.size();index++){ + for (int index = 0; index < headers.size(); index++) { try { - String key = headers.keyAt(index); + String key = headers.keyAt(index); String value = headers.get(key); if (value != null) { if (!general.StringIsEmptyOrNull(key) && !general.StringIsEmptyOrNull(value)) { @@ -68,37 +82,22 @@ public synchronized static void no_Auth( } } } catch (Exception e) { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - responder.onFailure(url,startTime,ErrorCode.RuntimeException); - } - }); + new Handler(Looper.getMainLooper()).post(() -> responder.onFailure(url, ErrorCode.RuntimeException)); } } client.newCall(request.build()).enqueue(new Callback() { @Override - public void onFailure(@NonNull Call call, final IOException e) { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - responder.onFailure(url,startTime,ErrorCode.ServerConnectionError); - } - }); + public void onFailure(@NonNull Call call, @NotNull IOException e) { + new Handler(Looper.getMainLooper()).post(() -> responder.onFailure(url, ErrorCode.ServerConnectionError)); } @Override public void onResponse(@NonNull Call call, @NonNull final Response response) { - responder.onResultHandler(startTime,response); + responder.onResultHandler(response); } }); } catch (Exception ex) { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - responder.onFailure(url,startTime,ErrorCode.RuntimeException); - } - }); + new Handler(Looper.getMainLooper()).post(() -> responder.onFailure(url, ErrorCode.RuntimeException)); } } @@ -109,38 +108,24 @@ public synchronized static void basic_Auth( @NonNull final AuthModel authModel, @NonNull final RequestParams params, @NonNull final ResultHandler responder) { - final Long startTime = getTimeMillisecond(); try { final ArrayMap headers = authModel.getHeaders(); - OAuth2Client auth = new OAuth2Client(client,headers,authModel); - auth.requestAccessToken(new OAuthResponseCallback() { - @Override - public void onResponse(OAuthResponse response) { - if (response.isSuccessful()) { - switch (authModel.getAuthType()){ - case BASIC_AUTH: - headers.put("Authorization", String.format("Bearer %s", response.getAccessToken())); - break; - } - authModel.setHeaders(headers); - no_Auth(client,url,tag,authModel,params,responder); - } else { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - responder.onFailure(url,startTime,ErrorCode.AuthorizationException); - } - }); + OAuth2Client auth = new OAuth2Client(client, headers, authModel); + auth.requestAccessToken(response -> { + if (response.isSuccessful()) { + switch (authModel.getAuthType()) { + case BASIC_AUTH: + headers.put("Authorization", String.format("Bearer %s", response.getAccessToken())); + break; } + authModel.setHeaders(headers); + no_Auth(client, url, tag, authModel, params, responder); + } else { + new Handler(Looper.getMainLooper()).post(() -> responder.onFailure(url, ErrorCode.AuthorizationException)); } }); } catch (Exception ex) { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - responder.onFailure(url,startTime,ErrorCode.RuntimeException); - } - }); + new Handler(Looper.getMainLooper()).post(() -> responder.onFailure(url, ErrorCode.RuntimeException)); } } } diff --git a/library/src/main/java/com/github/library/requestMethod/baseMethod.java b/library/src/main/java/com/github/library/requestMethod/baseMethod.java index f56c05a..e0cb59c 100644 --- a/library/src/main/java/com/github/library/requestMethod/baseMethod.java +++ b/library/src/main/java/com/github/library/requestMethod/baseMethod.java @@ -1,23 +1,14 @@ package com.github.library.requestMethod; -import android.content.ContentResolver; -import android.content.Context; -import android.net.Uri; -import android.webkit.MimeTypeMap; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; +import com.github.library.RestClient; +import com.github.library.helper.LogHelper; import java.util.concurrent.TimeUnit; -import com.github.library.helper.LogHelper; - - public abstract class baseMethod { + LogHelper logHelper = new LogHelper(RestClient.class); protected static String calcTime(Long startTime) { Long duration = getTimeMillisecond() - startTime; diff --git a/library/src/main/java/com/github/library/response/ResponseFileHandler.java b/library/src/main/java/com/github/library/response/ResponseFileHandler.java index 60bef27..eb5ef4f 100644 --- a/library/src/main/java/com/github/library/response/ResponseFileHandler.java +++ b/library/src/main/java/com/github/library/response/ResponseFileHandler.java @@ -13,36 +13,19 @@ public abstract class ResponseFileHandler extends ResultHandler { @Override - protected void onSuccess(String url, long startTime, final byte[] result) { - logHelper.d("url : " + url + " - time : " + calcTime(startTime) + " size : " + calcFileSize(result)); - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - onSuccess(result); - } - }); + protected void onSuccess(String url, byte[] result) { + new Handler(Looper.getMainLooper()).post(() -> onSuccess(result)); } @Override public void onProgress(final double percent, final long bytesWritten, final long totalSize) { super.onProgress(percent, bytesWritten, totalSize); - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - onProgress(percent, bytesWritten, totalSize); - } - }); + new Handler(Looper.getMainLooper()).post(() -> onProgress(percent, bytesWritten, totalSize)); } @Override - public void onFailure(String url, long startTime, final ErrorCode errorCode) { - logHelper.d("url : " + url + " - time : " + calcTime(startTime)); - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - onFailure(errorCode.getCode(), errorCode.getDescription()); - } - }); + public void onFailure(String url, final ErrorCode errorCode) { + new Handler(Looper.getMainLooper()).post(() -> onFailure(errorCode.getCode(), errorCode.getDescription())); } protected abstract void onSuccess(byte[] result); @@ -50,4 +33,4 @@ public void run() { public abstract void onFailure(int errorCode, String errorMsg); -} +} \ No newline at end of file diff --git a/library/src/main/java/com/github/library/response/ResponseJsonHandler.java b/library/src/main/java/com/github/library/response/ResponseJsonHandler.java index 11b9fbd..3954cba 100644 --- a/library/src/main/java/com/github/library/response/ResponseJsonHandler.java +++ b/library/src/main/java/com/github/library/response/ResponseJsonHandler.java @@ -23,75 +23,45 @@ public abstract class ResponseJsonHandler extends ResultHandler { String data = ""; @Override - protected void onSuccess(String url,long startTime, byte[] result) { + protected void onSuccess(String url, byte[] result) { try { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { data = new String(result, StandardCharsets.UTF_8); }else { data = new String(result,"UTF-8"); } - logHelper.d("url : " + url + " - time : " + calcTime(startTime) + " size : " + calcFileSize(result)); try { final Object object = new JSONTokener(data).nextValue(); if (object instanceof JSONObject){ - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - onSuccess((JSONObject) object); - } - }); + new Handler(Looper.getMainLooper()).post(() -> onSuccess((JSONObject) object)); }else if (object instanceof JSONArray){ - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - onSuccess((JSONArray) object); - } - }); + new Handler(Looper.getMainLooper()).post(() -> onSuccess((JSONArray) object)); }else { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - onSuccess(data); - } - }); + new Handler(Looper.getMainLooper()).post(() -> onSuccess(data)); } } catch (JSONException e) { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - onSuccess(data); - } - }); + new Handler(Looper.getMainLooper()).post(() -> onSuccess(data)); } } catch (UnsupportedEncodingException e) { - this.onFailure(url,startTime,ErrorCode.UnsupportedEncodingException); + this.onFailure(url,ErrorCode.UnsupportedEncodingException); } } @Override public void onProgress(final double percent, final long bytesWritten, final long totalSize) { super.onProgress(percent, bytesWritten, totalSize); - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - onProgress(percent,bytesWritten,totalSize); - } - }); + new Handler(Looper.getMainLooper()).post(() -> onProgress(percent,bytesWritten,totalSize)); } @Override - public void onFailure(String url, long startTime, final ErrorCode errorCode) { - logHelper.d("url : " + url + " - time : " + calcTime(startTime)); - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - onFailure(errorCode.getCode(),errorCode.getDescription()); - } - }); + public void onFailure(String url, final ErrorCode errorCode) { + new Handler(Looper.getMainLooper()).post(() -> onFailure(errorCode.getCode(),errorCode.getDescription())); } protected void onSuccess(JSONObject result){} + protected void onSuccess(JSONArray result){} + protected abstract void onSuccess(String result); public abstract void onFailure(int errorCode,String errorMsg); diff --git a/library/src/main/java/com/github/library/response/ResponseTextHandler.java b/library/src/main/java/com/github/library/response/ResponseTextHandler.java index 302f78e..de63d40 100644 --- a/library/src/main/java/com/github/library/response/ResponseTextHandler.java +++ b/library/src/main/java/com/github/library/response/ResponseTextHandler.java @@ -15,41 +15,24 @@ public abstract class ResponseTextHandler extends ResultHandler { @Override - protected void onSuccess(String url,long startTime, byte[] result) { + protected void onSuccess(String url, byte[] result) { try { final String value = new String(result,"UTF-8"); - logHelper.d("url : " + url + " - time : " + calcTime(startTime) + " size : " + calcFileSize(result)); - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - onSuccess(value); - } - }); + new Handler(Looper.getMainLooper()).post(() -> onSuccess(value)); } catch (UnsupportedEncodingException e) { - this.onFailure(url,startTime,ErrorCode.UnsupportedEncodingException); + this.onFailure(url,ErrorCode.UnsupportedEncodingException); } } @Override public void onProgress(final double percent, final long bytesWritten, final long totalSize) { super.onProgress(percent, bytesWritten, totalSize); - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - onProgress(percent,bytesWritten,totalSize); - } - }); + new Handler(Looper.getMainLooper()).post(() -> onProgress(percent,bytesWritten,totalSize)); } @Override - public void onFailure(String url, long startTime, final ErrorCode errorCode) { - logHelper.d("url : " + url + " - time : " + calcTime(startTime)); - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - onFailure(errorCode.getCode(),errorCode.getDescription()); - } - }); + public void onFailure(String url, final ErrorCode errorCode) { + new Handler(Looper.getMainLooper()).post(() -> onFailure(errorCode.getCode(),errorCode.getDescription())); } protected abstract void onSuccess(String result); diff --git a/library/src/main/java/com/github/library/utils/RequestParams.java b/library/src/main/java/com/github/library/utils/RequestParams.java index 0d97d3e..e325826 100644 --- a/library/src/main/java/com/github/library/utils/RequestParams.java +++ b/library/src/main/java/com/github/library/utils/RequestParams.java @@ -1,21 +1,22 @@ package com.github.library.utils; +import com.github.library.enums.RequestBodyType; +import com.github.library.helper.LogHelper; +import com.github.library.helper.general; +import com.github.library.model.FileModel; + import org.json.JSONException; import org.json.JSONObject; -import java.io.File; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; - -import com.github.library.enums.RequestBodyType; -import com.github.library.helper.LogHelper; -import com.github.library.helper.general; -import com.github.library.model.FileModel; +import java.util.Objects; import okhttp3.FormBody; import okhttp3.MediaType; +import okhttp3.MultipartBody; import okhttp3.RequestBody; @@ -36,119 +37,136 @@ public class RequestParams { private LinkedHashMap> paramsArray = new LinkedHashMap<>(); - private RequestBodyType type = RequestBodyType.FormData; + private RequestBodyType type; private LogHelper logHelper = new LogHelper(RequestBody.class); public RequestParams() { - + this.type = RequestBodyType.FormUrlEncode; } public RequestParams(RequestBodyType type) { this.type = type; } - public void put(String plainText){ + public void put(String plainText) { this.plainText = plainText; } - public void put(String contentType,byte[] binaryInput){ + public void put(String contentType, byte[] binaryInput) { this.contentType = contentType; this.binaryInput = binaryInput; } + public void put(String key, Object value) { + if (general.StringIsEmptyOrNull(key)) { + return; + } + params.put(key, value); + } + public void put(String key, String value) { - if (general.StringIsEmptyOrNull(key) || general.StringIsEmptyOrNull(value)){ + if (general.StringIsEmptyOrNull(key) || general.StringIsEmptyOrNull(value)) { return; } params.put(key, value); } public void put(String key, Integer value) { - if (general.StringIsEmptyOrNull(key) || value == null){ + if (general.StringIsEmptyOrNull(key) || value == null) { + return; + } + params.put(key, value); + } + + public void put(String key, Long value) { + if (general.StringIsEmptyOrNull(key) || value == null) { return; } params.put(key, value); } public void put(String key, Float value) { - if (general.StringIsEmptyOrNull(key) || value == null){ + if (general.StringIsEmptyOrNull(key) || value == null) { return; } params.put(key, value); } public void put(String key, Double value) { - if (general.StringIsEmptyOrNull(key) || value == null){ + if (general.StringIsEmptyOrNull(key) || value == null) { return; } params.put(key, value); } - public void put(String key, FileModel value){ - if (general.StringIsEmptyOrNull(key) || value == null){ + public void put(String key, FileModel value) { + if (general.StringIsEmptyOrNull(key) || value == null) { return; } - fileParams.put(key,value); + fileParams.put(key, value); } public void put(String key, boolean value) { - if (general.StringIsEmptyOrNull(key)){ + if (general.StringIsEmptyOrNull(key)) { return; } params.put(key, value); } public void put(String key, JSONObject value) { - if (general.StringIsEmptyOrNull(key) || value == null){ + if (general.StringIsEmptyOrNull(key) || value == null) { return; } params.put(key, value); } public void put(String key, List values) { - if (general.StringIsEmptyOrNull(key) || values == null){ + if (general.StringIsEmptyOrNull(key) || values == null) { return; } if (paramsArray.get(key) != null) { List items = paramsArray.get(key); - values.addAll(items); + if (items != null) + values.addAll(items); } paramsArray.put(key, values); } - public void add(String key, List values){ - if (general.StringIsEmptyOrNull(key) || values == null){ + public void add(String key, List values) { + if (general.StringIsEmptyOrNull(key) || values == null) { return; } - if (paramsArray.get(key) != null){ - values.addAll(paramsArray.get(key)); + if (paramsArray.get(key) != null) { + values.addAll(Objects.requireNonNull(paramsArray.get(key))); } - paramsArray.put(key,values); + paramsArray.put(key, values); } - public void putContent(String key, List values){ - if (general.StringIsEmptyOrNull(key) || values == null){ + public void putContent(String key, List values) { + if (general.StringIsEmptyOrNull(key) || values == null) { return; } ArrayList items = new ArrayList<>(); - if (paramsArray.get(key) != null){ - items.addAll(paramsArray.get(key)); + if (paramsArray.get(key) != null) { + items.addAll(Objects.requireNonNull(paramsArray.get(key))); } - for (Object item : values){ + for (Object item : values) { items.add(item.toString()); } - paramsArray.put(key,items); + paramsArray.put(key, items); } public void add(String key, String value) { - if (general.StringIsEmptyOrNull(key) || value == null){ + if (general.StringIsEmptyOrNull(key) || value == null) { return; } ArrayList values; if (paramsArray.get(key) != null) { values = (ArrayList) paramsArray.get(key); - values.add(value); + if (values != null) { + values.add(value); + } } else { values = new ArrayList<>(); values.add(value); @@ -157,52 +175,84 @@ public void add(String key, String value) { } public RequestBody getRequestForm() { - switch (type){ + if (getFileParams().size() > 0) { + //for post File You should choose Multipart Type + type = RequestBodyType.MultiPart; + } + switch (type) { case RawTEXTPlain: return RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), plainText); case RawJSON: JSONObject object = new JSONObject(); try { - for (String key : params.keySet()) { - object.put(key, params.get(key)); + for (String key : getParams().keySet()) { + object.put(key, getParams().get(key)); } - for (String key : paramsArray.keySet()) { - for (Object item : paramsArray.get(key)) { + for (String key : getParamsArray().keySet()) { + for (Object item : Objects.requireNonNull(getParamsArray().get(key))) { object.put(key, item); } } } catch (JSONException e) { - //throw new JSONException("Exception During Create JSON"); logHelper.e(e); } return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), object.toString()); case Binary: - return RequestBody.create(MediaType.parse(contentType),(byte[]) binaryInput); - default: //FormData + return RequestBody.create(MediaType.parse(contentType), binaryInput); + case MultiPart: + MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM); + for (String key : getParams().keySet()) { + builder.addFormDataPart(key, (String) Objects.requireNonNull(getParams().get(key))); + } + for (String key : getParamsArray().keySet()) { + for (Object item : Objects.requireNonNull(getParamsArray().get(key))) { + builder.addFormDataPart(key, (String) item); + } + } + LinkedHashMap fileParams = getFileParams(); + for (String key : fileParams.keySet()) { + FileModel uploadFile = fileParams.get(key); + if (uploadFile != null) { + builder.addFormDataPart(key, uploadFile.getFilenName(), RequestBody.create(uploadFile.getMimeType(), uploadFile.getFile())); + } + } + return builder.build(); + case FormData: + case FormUrlEncode: + default: { FormBody.Builder formBody = new FormBody.Builder(); for (String key : params.keySet()) { - formBody.addEncoded(key, params.get(key).toString()); + formBody.addEncoded(key, String.valueOf(params.get(key))); } for (String key : paramsArray.keySet()) { - for (Object item : paramsArray.get(key)) { + for (Object item : Objects.requireNonNull(paramsArray.get(key))) { formBody.addEncoded(key, item.toString()); } } return formBody.build(); + } } } - public LinkedHashMap getParams() { + public RequestBodyType getType() { + return type; + } + + private LinkedHashMap getParams() { return params; } - public LinkedHashMap getFileParams() { + private LinkedHashMap getFileParams() { return fileParams; } + private LinkedHashMap> getParamsArray() { + return paramsArray; + } + public void setParamsArray(LinkedHashMap> paramsArray) { - if (paramsArray == null){ + if (paramsArray == null) { return; } this.paramsArray = paramsArray;