這是一個Android Library,方便developer開發Android App時,快速執行下載或上傳Json file,讓你使用Json進行資料傳輸有如piece of cake。
導入 RxJava2。重新簡介目前功能
- 使用 RxJava2 (v2.0.2)
- 使用 Stetho (v1.3.1) 套件,可利用 Network Inspection 瀏覽 api call 的資訊
- 共用 Golbal
OkHttpClient
- 先自訂 Global 的
OkHttpClient
。通常 app 只需要呼叫一次即可
// This is sample of build a OkhttpClient.
// All these setting are optional.
OkHttpClient client = new OkHttpClient.Builder()
.addNetworkInterceptor(new StethoInterceptor())
.connectTimeout(timeout, TimeUnit.SECONDS)
.readTimeout(timeout, TimeUnit.SECONDS)
.writeTimeout(timeout, TimeUnit.SECONDS)
.build();
ClientHelper.setupOkHttpClient(client);
- 呼叫
JsonCake
JsonCake jsonCake = new JsonCake.Builder()
.urlStr("YOUR_URL")
.build();
jsonCake.start()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableObserver<String>() {
@Override
public void onNext(String value) {
// Get your result here
Log.d(TAG,value);
}
@Override
public void onError(Throwable e) {
Log.e(TAG,e.toString());
}
@Override
public void onComplete() {
}
});
你可以利用 JsonCake
設定一些參數
// This is okhttp object for http post
MultipartBody.Builder bodybuilder =
new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("data",data);
// This is okhttp object for http post
RequestBody requestBody = bodybuilder.build();
JsonCake jsonCake = new JsonCake.Builder()
.urlStr("YOUR_URL")
.showingJson(true) // true if you want to log the json string
.formBody(requestBody) // set form data if you want to do http-post
.build();
導入了 Stetho 套件 (com.facebook.stetho:stetho-okhttp3:1.3.1
)
可以直接利用瀏覽器查看 Network Request/Response
只需要在 Application
啟用 Stetho 即可,如下範例:
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
Stetho.initializeWithDefaults(this);
}
}
repositories {
maven {
url "http://dl.bintray.com/badu/maven"
}
}
...
dependencies {
...
compile 'com.crazyma.jsoncake:jsoncake:2.2.0'
}
此Library所使用的dependencies:
compile 'com.squareup.okhttp3:okhttp:3.3.1'
compile 'com.facebook.stetho:stetho-okhttp3:1.3.1'
compile 'io.reactivex.rxjava2:rxjava:2.0.2'
<uses-permission android:name="android.permission.INTERNET">
本Library以AsyncTask為基礎建立,使用了 OKHttp 以及 Gson 協助處理相關的操作。
Required
Name | Data type | Description |
---|---|---|
urlStr | String | json file 的網址。 |
onFinishListener | OnFinishListener | Task 結束時呼叫的Listener。 |
Optional
Name | Data type | Description |
---|---|---|
connectionTimeout | int | 連線至server的timeout時間,單位是秒。 |
readTimeout | int | Http get 的 timeout時間,單位是秒。 |
writeTimeout | int | Http post 的timeout時間,單位是秒。 |
delay | int | 延遲送出http request,單位是秒 |
onTaskFailListener | OnTaskFailListener | Task 失敗時呼叫的Listener。 |
formBody | RequestBody | Http post所使用。是OkHttp所定義的類別。 |
objectType | Type | 類別型態。配合Gson使用。 |
pool | ExecutorService | 設定AsyncTask的Executor。詳情請參閱官網 |
showingJson | boolean | 指示是否要Log response。 |
CakeConfig
你可以於app初始設定一些參數,讓所有的Task共用此設定
CakeConfig.getInstance()
.setConnectionTimeout(10);
.setDelay(1)
.setPool(Executors.newFixedThreadPool(5));
/* 此JsonCake Task會自動帶入上述設定 */
JsonCake.setUrl("you_url")
.setOnFinishListener(new OnFinishLoadStringListener() {
@Override
public void onFinish(String responseStr) {
}
})
.get();
Note: 如果設定CakeConfig的同時,也在JsonCake設定相關參數,會以最後的設定為參考依據。
JsonCake.setUrl("your_json_file_url")
.setOnFinishListener(new OnFinishLoadJsonObjectListener(){
@Override
public void onFinish(JSONObject arg0) {
// TODO Auto-generated method stub
/* write your code here */
}
})
.get();
JsonCake.setUrl("your_json_file_url")
.setReadTimeout(5)
.setOnFinishListener(new OnFinishLoadJsonArrayListener(){
@Override
public void onFinish(JSONArray arg0) {
// TODO Auto-generated method stub
/* write your code here */
}
})
.get();
JsonCake.setUrl("your_json_file_url")
.setOnFinishListener(new OnFinishLoadStringListener(){
@Override
public void onFinish(String arg0) {
// TODO Auto-generated method stub
/* write your code here */
}
})
.setOnTaskFailListener(new OnTaskFailListener(){
@Override
public void onFail(String errorMessage, Exception exception) {
// TODO Auto-generated method stub
/* write your code here */
}
})
.get();
####Load Custom Object parsed by Gson
JsonCake.setUrl("your_json_file_url")
.setObjectType(DataSet.class)
.setOnFinishListener(new OnFinishLoadObjectListener(){
@Override
public void onFinish(Object object) {
// TODO Auto-generated method stub
DataSet dataSet = (DataSet)object;
/* write your code here */
}
})
.get();
Note: DataSet是自己定義的class。Gson可以把下載的Json解析成DataSet Object。詳情請參考官網。
####Send Http Post and Get String Response
RequestBody formBody = new FormEncodingBuilder()
.add("Name", "Tom") // key-value pair in POST
.add("Age", "25")
.build();
JsonCake.setUrl("your_url")
.setOnFinishListener(new OnFinishLoadStringListener(){
@Override
public void onFinish(String responseStr) {
// TODO Auto-generated method stub
/* write your code here */
}
})
.setFormBody(formBody)
.post();
Note: RequestBody 是 OkHttp所定義的Class,可以依序將Form的資料依序填入。詳情請參考官網。
####Cancel Task
GetTask *getTask = JsonCake.setUrl("your_url")
.setOnFinishListener(...)
.get();
/* your cord... */
getTask.cancel();
repositories {
maven {
url "http://dl.bintray.com/badu/maven"
}
}
...
dependencies {
...
compile 'com.crazyma.jsoncake:jsoncake:1.0.3'
}
此Library所使用的dependencies:
compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.google.code.gson:gson:2.3.1'
<uses-permission android:name="android.permission.INTERNET">
Copyright 2016 David Ma
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.