天天看點

Okgo學習 get和post請求(1)

OkGo是封裝了okhttp的網絡架構,可以與RxJava完美結合,比Retrofit更簡單易用。

作者自己認為okgo做網絡請求更快捷比較簡單。

直接上代碼。

第一步在Module的build.gradle:

dependencies {

//必須使用
implementation 'com.lzy.net:okgo:3.0.4'
implementation 'com.lzy.net:okrx:1.0.2'
implementation 'com.lzy.net:okserver:2.0.5'
implementation 'com.google.code.gson:gson:2.2.4'
           

}

第二步自定義類繼承Application:

public class MyApp extends Application {

    public static MyApp myApp;
	
    @Override
    public void onCreate() {
        super.onCreate();

        myApp=this;
        //初始化Okgo 友善全局使用。
        OkGo.getInstance().init(this);

    }
    //必須在清單檔案聲明  android:name=".MyApp"
    public static MyApp getInstance(){
        return  myApp;
    }
}

           

第三步 設定兩個按鈕分别設定監聽事件網絡請求 直接TextView顯示資料

GET請求:

OkGo.<String>get("https://www.wanandroid.com/article/list/1/json")//
                        .tag(this)
                        .cacheKey("cachekey")//作為緩存的key
                        .cacheMode(CacheMode.NO_CACHE)//設定緩存模式

                        //StringCallback隻傳回成功
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                String body = response.body();
                                Gson gson = new Gson();
                                JokeBean bean = gson.fromJson(body, JokeBean.class);
                                request_content.setText("Get請求" + bean.getData().getDatas().toString());
                            }

                            @Override//擴充卡模式,可以不實作該方法
                            public void onError(Response<String> response) {

                            }
                        });
           

POST請求:

HttpParams params = new HttpParams();
                				params.put("pno", 2);
                				params.put("ps", 20);
                				params.put("dtype", "json");
                				params.put("key", "70fe6c3345e3061c7918fe8bdb7ea42c");
              	OkGo.<String>post("https://v.juhe.cn/weixin/query")
                        .tag(this)
                        .params(params)//傳入請求參數
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                String body = response.body();
                                Gson gson = new Gson();
                             	 WanAndroidBean bean = gson.fromJson(body, 	WanAndroidBean.class);
                                if (bean.getResult().getList() != null) {
                                    request_content.setText("Post請求" + bean.getResult().getList().get(1).toString());
                                }
                            }
                        });
           

另附效果圖:

Okgo學習 get和post請求(1)
Okgo學習 get和post請求(1)

一定要在清單檔案添加網絡權限!

最後祝大家在工作中進步,學習中進步。我們共同進步。