Retrofit + RxJava,Http請求get和post方法獲取json數(shù)據(jù)簡單封裝

Retrofit + RxJava這兩個組合起來真的炒雞好用,只是可能第一步比較難踏出去,剛開始不太理解這兩個東西是什么,后來是看了這篇文章:
http://gank.io/post/560e15be2dca930e00da1083

原理就不介紹了,上面那個是很好的資料

一、首先要用到Retrofit和RxJava通常需要用到以下依賴

compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'io.reactivex:rxjava:1.1.6'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.google.code.gson:gson:2.7'

另:因為這里還要處理json數(shù)據(jù)我用的是以下的庫

compile group: 'com.alibaba', name: 'fastjson', version: '1.2.22'

如果想查這些庫的其他版本給個網(wǎng)址(以前居然不知道,一直是各種搜索。。)

http://mvnrepository.com/

二、因為需要連接網(wǎng)絡,不要忘了配置網(wǎng)絡權限

三、封裝的代碼

public interface HttpApi {
    @FormUrlEncoded
    @POST("{path}")
    Observable<JSONObject> post(@Path("path") String path, @FieldMap Map<String, String> map);
    @FormUrlEncoded
    @POST("{root}/{path}")
    Observable<JSONObject> post(@Path("root") String root, @Path("path") String path, @FieldMap Map<String, String> map);

    @FormUrlEncoded
    @POST("{root}/{path}")
    Observable<JSONObject> post(@Path("root") String root, @Path("path") String path);
    @FormUrlEncoded
    @POST("{path}")
    Observable<JSONObject> post(@Path("path") String path);

    @GET("{path}")
    Observable<JSONObject> get(@Path("path") String path);

    @GET("{path}")
    Observable<JSONObject> get(@Path("path") String path, @QueryMap Map<String, String> map);
}

public class HttpRequests {
    private static String baseUrl = "http://127.0.0.1:8080";
    private static HttpRequests instance = null;
    private HttpApi httpService;

    public static HttpRequests getInstance() {
        if (instance == null) {
            synchronized (HttpRequests.class) {
                if (instance == null) {
                    instance = new HttpRequests();
                }
            }
        }
        return instance;
    }

    private HttpRequests() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        httpService = retrofit.create(HttpApi.class);
    }

    public Observable post(String path, Map<String, String> map) {
        try {
                Observable<JSONObject> observable;
            if (path.split("/").length > 1) {
                String root = path.split("/")[0];
                path = path.split("/")[1];
                if (map != null)
                    observable = httpService.post(root, path, map);
                else
                    observable = httpService.post(root, path);
            } else if (map != null)
                observable = httpService.post(path, map);
            else
                observable = httpService.post(path);
            observable.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread());
            return observable;
        } catch (Exception e) {
            Log.e("error", e.getMessage());
            return null;
        }
    }

    public Observable get(String path, Map<String, String> map) {
        try {
                Observable<JSONObject> observable;
            if (map != null) {
                observable = httpService.get(path, map);
            } else {
                observable = httpService.get(path);
            }
            observable.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread());
            return observable;
        } catch (Exception e) {
            Log.e("lawliex", e.getMessage());
            return null;
        }
    }

}

四、 使用方法

    //假設我們要請求的地址是http://localhost:8080/path
    //map用來保存請求參數(shù)
    //post方法的的第一個參數(shù)path是我們請求url的path
    Map<String,String> map = new HashMap<>();
    map.put("id","id");    
    map.put("ticket","ticket");
    
    HttpRequests.getInstance().post("path",map)
            .subscribe(new Subscriber<JSONObject>() {
                @Override
                public void onCompleted() {

                }
                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(JSONObject jsonObject) {
                    //jsonObject就是我們獲取到的json數(shù)據(jù)
                    //在這里可以做一些成功獲取數(shù)據(jù)的操作
                }
            });
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容