Skip to content

Commit

Permalink
update Post File
Browse files Browse the repository at this point in the history
update Authorization Oauth2 and Basic
  • Loading branch information
shatergholi authored and shatergholi committed Jun 16, 2019
1 parent 82b3587 commit 2c2c3d4
Show file tree
Hide file tree
Showing 27 changed files with 349 additions and 485 deletions.
29 changes: 0 additions & 29 deletions .idea/codeStyles/Project.xml

This file was deleted.

8 changes: 8 additions & 0 deletions .idea/dictionaries/alishatergholi.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions .idea/encodings.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 2 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ RestClient
Type-safe HTTP client for Android and Java by Square, Inc.


implement Basic Authorization
implement Oauth2 Authorization


download
Expand All @@ -25,7 +25,7 @@ latest version on jitpack [![](https://jitpack.io/v/alishatergholi/RestClient.sv
}
dependencies {
implementation 'com.github.alishatergholi:rest-client:[latest-version](https://github.com/alishatergholi/rest-client/releases/latest)'
implementation 'com.github.alishatergholi:rest-client:1.1.2'
}
```

Expand All @@ -37,9 +37,6 @@ How do i use RestClient
```java
RestClient client = new RestClient
.Builder(context)
/* you can add Accept encoding for encode your response */
/* for now we just support gzip */
.setAcceptEnconding(EncodingType.GZIP)
/* for add custom header you need
ArrayMap<String,String> header = new ArrayMap<>();
header.put("appid","0e8f8fd2-1acb-11e7-8ab0-ac162d7938f0");
Expand Down
12 changes: 6 additions & 6 deletions app/src/main/java/com/github/restclient/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ protected void onCreate(Bundle savedInstanceState) {

initRestClient();

//{"album":{"album_type":"album","artists":[{"external_urls":{"spotify":"https:\/\/open.spotify.com\/artist\/08td7MxkoHQkXnWAYD8d6Q"},"href":"https:\/\/api.spotify.com\/v1\/artists\/08td7MxkoHQkXnWAYD8d6Q","id":"08td7MxkoHQkXnWAYD8d6Q","name":"Tania Bowra","type":"artist","uri":"spotify:artist:08td7MxkoHQkXnWAYD8d6Q"}],"available_markets":["AD","AE","AR","AT","AU","BE","BG","BH","BO","BR","CA","CH","CL","CO","CR","CY","CZ","DE","DK","DO","DZ","EC","EE","EG","ES","FI","FR","GB","GR","GT","HK","HN","HU","ID","IE","IL","IN","IS","IT","JO","JP","KW","LB","LI","LT","LU","LV","MA","MC","MT","MX","MY","NI","NL","NO","NZ","OM","PA","PE","PH","PL","PS","PT","PY","QA","RO","SA","SE","SG","SK","SV","TH","TN","TR","TW","US","UY","VN","ZA"],"external_urls":{"spotify":"https:\/\/open.spotify.com\/album\/6akEvsycLGftJxYudPjmqK"},"href":"https:\/\/api.spotify.com\/v1\/albums\/6akEvsycLGftJxYudPjmqK","id":"6akEvsycLGftJxYudPjmqK","images":[{"height":640,"url":"https:\/\/i.scdn.co\/image\/a529b65b4bd322b16bee34672ce45278e890e176","width":640},{"height":300,"url":"https:\/\/i.scdn.co\/image\/985cc10acdbbedb6a16d7c74f9e23553e2b28dbc","width":300},{"height":64,"url":"https:\/\/i.scdn.co\/image\/37b46a2662c09502885d1804c1c865b199cc3d67","width":64}],"name":"Place In The Sun","release_date":"2004-02-02","release_date_precision":"day","total_tracks":11,"type":"album","uri":"spotify:album:6akEvsycLGftJxYudPjmqK"},"artists":[{"external_urls":{"spotify":"https:\/\/open.spotify.com\/artist\/08td7MxkoHQkXnWAYD8d6Q"},"href":"https:\/\/api.spotify.com\/v1\/artists\/08td7MxkoHQkXnWAYD8d6Q","id":"08td7MxkoHQkXnWAYD8d6Q","name":"Tania Bowra","type":"artist","uri":"spotify:artist:08td7MxkoHQkXnWAYD8d6Q"}],"available_markets":["AD","AE","AR","AT","AU","BE","BG","BH","BO","BR","CA","CH","CL","CO","CR","CY","CZ","DE","DK","DO","DZ","EC","EE","EG","ES","FI","FR","GB","GR","GT","HK","HN","HU","ID","IE","IL","IN","IS","IT","JO","JP","KW","LB","LI","LT","LU","LV","MA","MC","MT","MX","MY","NI","NL","NO","NZ","OM","PA","PE","PH","PL","PS","PT","PY","QA","RO","SA","SE","SG","SK","SV","TH","TN","TR","TW","US","UY","VN","ZA"],"disc_number":1,"duration_ms":276773,"explicit":false,"external_ids":{"isrc":"AUCR10410001"},"external_urls":{"spotify":"https:\/\/open.spotify.com\/track\/2TpxZ7JUBn3uw46aR7qd6V"},"href":"https:\/\/api.spotify.com\/v1\/tracks\/2TpxZ7JUBn3uw46aR7qd6V","id":"2TpxZ7JUBn3uw46aR7qd6V","is_local":false,"name":"All I Want","popularity":1,"preview_url":"https:\/\/p.scdn.co\/mp3-preview\/12b8cee72118f995f5494e1b34251e4ac997445e?cid=50ff9f0569f0439087bbc05acb38db43","track_number":1,"type":"track","uri":"spotify:track:2TpxZ7JUBn3uw46aR7qd6V"}

findViewById(R.id.text).setOnClickListener(view -> {
RequestParams params = new RequestParams(RequestBodyType.FormData);
Expand Down Expand Up @@ -67,13 +66,14 @@ public void onFailure(int errorCode, String errorMsg) {

private void initRestClient() {
ArrayMap<String, String> header = new ArrayMap<>();

String clientId = "50ff9f0569f0439087bbc05acb38db43";
String clientSecret = "785e208d5eef44a28941bf47146c0873";

header.put("Content-Type", "application/x-www-form-urlencoded");

restClient = new RestClient.Builder(this)
.setAuthorization(
"",
"",
"",
AuthType.BASIC_AUTH)
.setAuthorizationOauth2("https://accounts.spotify.com/api/token",clientId,clientSecret)
.setDebugEnable(true)
.setHeader(header)
.build();
Expand Down
6 changes: 3 additions & 3 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,16 @@ buildscript {
extra.set("compileSdk" , 28)
extra.set("targetSdk" , 28)
extra.set("buildTools" , "28.0.3")
extra.set("version_code" , 11)
extra.set("version_name" , "1.1.1")
extra.set("version_code" , 12)
extra.set("version_name" , "1.1.2")

repositories {
google()
jcenter()
maven("https://jitpack.io")
}
dependencies {
classpath("com.android.tools.build:gradle:3.3.2")
classpath("com.android.tools.build:gradle:3.4.1")
classpath("com.github.dcendents:android-maven-gradle-plugin:2.1")
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
Expand Down
6 changes: 3 additions & 3 deletions library/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ dependencies {
implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar"))))
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("com.squareup.okhttp3:okhttp:3.14.2")
testImplementation("junit:junit:4.12")
androidTestImplementation("androidx.test:runner:1.1.1")
androidTestImplementation("androidx.test.espresso:espresso-core:3.1.1")
androidTestImplementation("androidx.test:runner:1.2.0")
androidTestImplementation("androidx.test.espresso:espresso-core:3.2.0")

}
134 changes: 134 additions & 0 deletions library/src/main/java/com/github/library/BaseClient.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
package com.github.library;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import androidx.collection.ArrayMap;

import com.github.library.enums.AuthType;
import com.github.library.helper.LogHelper;
import com.github.library.model.AuthModel;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

abstract class BaseClient {

WeakReference<Context> appContext;

String clientId;
String clientSecret;
String site;

String token;

String grantType;

String username;
String password;

AuthType authType;

ArrayMap<String,String> headers;

int timeMilliSecond = 60;

boolean debugEnable = true;

private static OkHttpClient instance;

static synchronized OkHttpClient getClient(int timeOut, boolean enableDebug) {
if (instance == null) {
instance = new OkHttpClient()
.newBuilder()
.connectTimeout(timeOut, TimeUnit.MILLISECONDS)
.build();

if (enableDebug) {
instance.newBuilder()
.addInterceptor(new LoggingInterceptor())
.build();
}
}
return instance;
}

public void cancelAllRequest() {
for (Call call : getClient(timeMilliSecond,debugEnable).dispatcher().queuedCalls()) {
call.cancel();
}
}

public void cancelCallWithTag(String tag) {
for (Call call : getClient(timeMilliSecond,debugEnable).dispatcher().queuedCalls()) {
try {
Object item = call.request().tag();
if (item != null){
if (item.equals(tag))
call.cancel();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

private static class LoggingInterceptor implements Interceptor {

LogHelper logHelper = new LogHelper(RestClient.class);

@SuppressLint("DefaultLocale")
@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;
}
}

boolean checkNetworkConnection(Context context) {
try {
if (context == null) {
return false;
}
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null) {
return true;
}
NetworkInfo nwInfo = connectivityManager.getActiveNetworkInfo();
return nwInfo == null || !nwInfo.isConnectedOrConnecting();
} catch (Exception ex) {
return true;
}
}

AuthModel getAuthModel(){
AuthModel auth = new AuthModel();
auth.setClientId(this.clientId);
auth.setClientSecret(this.clientSecret);
auth.setSite(this.site);
auth.setToken(this.token);
auth.setGrantType(this.grantType);
auth.setUsername(this.username);
auth.setPassword(this.password);
auth.setAuthType(this.authType);
auth.setHeaders(this.headers);
return auth;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ public interface AuthorizationParams {
String POST_PASSWORD = "password";
String POST_CLIENT_ID = "client_id";
String POST_CLIENT_SECRET = "client_secret";
String POST_SCOPE = "scope";
String POST_TOKEN = "token";
String POST_REFRESH_TOKEN = "refresh_token";
String HEADER_CONTENT_TYPE = "Content-Type";
String HEADER_AUTHORIZATION = "Authorization";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
package com.github.library.Interface;




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 okhttp3.Response;
import okhttp3.ResponseBody;
Expand All @@ -23,39 +20,21 @@ public abstract class ResultHandler {
public void onResultHandler(Response response){
String url = response.request().url().url().toString();
if (response.body() != null && response.isSuccessful()) {
InputStream inputStream = null;
String contentEncodingHeader = response.header("Content-Encoding");
ResponseBody body = response.body();
if (body != null) {
if (contentEncodingHeader != null && contentEncodingHeader.equals("gzip")) {
try {
inputStream = new GZIPInputStream(body.byteStream());
} catch (IOException e) {
this.onFailure(url,ErrorCode.IOException);
}
} else {
inputStream = body.byteStream();
}
if (inputStream != null){
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int next = inputStream.read();
while (next > -1){
outputStream.write(next);
next = inputStream.read();
}
outputStream.flush();
byte[] result = outputStream.toByteArray();
outputStream.close();
this.onSuccess(url,result);
} catch (IOException e) {
this.onFailure(url,ErrorCode.IOException);
}
}else {
this.onFailure(url,ErrorCode.ParseException);
InputStream inputStream = body.byteStream();
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int next = inputStream.read();
while (next > -1){
outputStream.write(next);
next = inputStream.read();
}
} else {
this.onFailure(url,ErrorCode.NullPointerException);
outputStream.flush();
byte[] result = outputStream.toByteArray();
outputStream.close();
this.onSuccess(url,result);
} catch (IOException e) {
this.onFailure(url,ErrorCode.IOException);
}
} else {
this.onFailure(url,ErrorCode.Parse(response.code()));
Expand Down
Loading

0 comments on commit 2c2c3d4

Please sign in to comment.