亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

android實現(xiàn)okHttp的get和post請求的簡單封裝與使用

 更新時間:2021年05月06日 10:58:33   作者:會飛的種花家  
這篇文章主要介紹了android實現(xiàn)okHttp的get和post請求的簡單封裝與使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

由于Android課程項目需要,特地查閱了okHttp的使用,發(fā)現(xiàn)網(wǎng)上找的大多和自己的需求不一樣。所以就著團隊項目需要,自己簡單封裝了一個okHttp的get和post請求。

話不多說,直接看代碼吧!

一、前期需要用到的屬性封裝

private static Request request = null;
    private static Call call = null;
    private static int TimeOut = 120;
    //單例獲取ohttp3對象
    private static OkHttpClient client = null;
    /**
     * OkHttpClient的構(gòu)造方法,通過線程鎖的方式構(gòu)造
     * @return OkHttpClient對象
     */
    private static synchronized OkHttpClient getInstance() {
        if (client == null) {
            client = new OkHttpClient.Builder()
                    .readTimeout(TimeOut, TimeUnit.SECONDS)
                    .connectTimeout(TimeOut, TimeUnit.SECONDS)
                    .writeTimeout(TimeOut, TimeUnit.SECONDS)
                    .build();
        }
        return client;
    }

    /**
     * callback接口
     * 異步請求時使用
     */
    static class MyCallBack implements Callback {
        private OkHttpCallback okHttpCallBack;

        public MyCallBack(OkHttpCallback okHttpCallBack) {
            this.okHttpCallBack = okHttpCallBack;
        }

        @Override
        public void onFailure(Call call, IOException e) {
            okHttpCallBack.onFailure(e);
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            okHttpCallBack.onSuccess(response);
        }
    }
    /**
     * 獲得同步get請求對象Response
     * @param url
     * @return Response
     */
    private static Response doSyncGet(String url) {
        //創(chuàng)建OkHttpClient對象
        client = getInstance();
        request = new Request.Builder()
                .url(url)//請求鏈接
                .build();//創(chuàng)建Request對象
        try {
            //獲取Response對象
            Response response = client.newCall(request).execute();
            return response;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 獲得異步get請求對象
     * @param url      請求地址
     * @param callback 實現(xiàn)callback接口
     */
    private static void doAsyncGet(String url,OkHttpCallback callback) {
        MyCallBack myCallback = new MyCallBack(callback);
        client = getInstance();
        request = new Request.Builder()
                .url(url)
                .get()
                .build();
        client.newCall(request).enqueue(myCallback);
    }

其中,OKHttpCallback接口為:

import java.io.IOException;
import okhttp3.Response;

public interface OkHttpCallback {
    void onFailure(IOException e);
    void onSuccess(Response response);
}

二、get請求封裝

1.項目需求是全程使用json格式的字符串進行交互,所以以下是針對json來封裝的。
2.在這里說明一下,返回的是字符串類型,表示后臺返回的json字符串,另外,為什么要用list來定義返回值result,result.get(0)為return值,因為直接用String來定義result會報錯,具體原因未知。。。。

(1)同步get請求

    /**
     * 同步get請求
     * 例如:請求的最終地址為:http://127.0.0.1:8081/user/getUser/123
     * @param url 基本請求地址   例子: http://127.0.0.1:8081
     * @param args 請求的參數(shù)    args[]=new String[]{"user","getUser","123"}
     * @return String
     */
    public static String getSyncRequest(String url,String... args) {
        List<String> result=new ArrayList<>();//返回值
        String address=url;
        for(int i=0;i<args.length;i++){
            address=address+"/"+args[i];
        }
        final String finalAddress = address;
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response finalResponse = doSyncGet(finalAddress);
                String res = null;
                try {
                    Log.d("同步get請求請求地址:",finalAddress);
                    if (finalResponse.isSuccessful()) {//請求成功
                        ResponseBody body = finalResponse.body();//拿到響應(yīng)體
                        res = body.string();
                        result.add(res);
                        Log.d("HttpUtil", "同步get請求成功!");
                        Log.d("請求對象:", res);
                    } else {
                        Log.d("HttpUtil", "同步get請求失??!");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        /**因為函數(shù)返回是立刻執(zhí)行的,而result要在請求完成之后才能獲得
         * 所以需要等待result獲得返回值之后再執(zhí)行return*/
        while(result.size()==0){
            try {
                TimeUnit.MILLISECONDS.sleep(10);//等待xx毫秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return result.get(0);
    }

(2)異步get請求
 

   /**
     * 異步get請求
     * 例如:請求的最終地址為:http://127.0.0.1:8081/user/getUser/123
     * @param url 基本請求地址   例子: http://127.0.0.1:8081
     * @param args 請求的參數(shù)    args[]=new String[]{"user","getUser","123"}
     * @return String
     */
    public static String getAsyncRequest(String url,String... args){
        List<String> result=new ArrayList<>();
        String address=url;
        for(int i=0;i<args.length;i++){
            address=address+"/"+args[i];
        }
        final String finalAddress = address;
        doAsyncGet(finalAddress, new OkHttpCallback() {
            @Override
            public void onFailure(IOException e) {
                Log.d("異步get請求地址:",finalAddress);
                Log.d("HttpUtil", "異步get請求失??!");
            }
            @Override
            public void onSuccess(Response response) {
                Log.d("異步get請求地址:",finalAddress);
                String res = null;
                try {
                    res = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                result.add(res);
                Log.d("HttpUtil", "異步get請求成功!");
                Log.d("請求對象:", res);
            }
        });
        /**因為函數(shù)返回是立刻執(zhí)行的,而result要在請求完成之后才能獲得
         * 所以需要等待result獲得返回值之后再執(zhí)行return*/
        while(result.size()==0){
            try {
                TimeUnit.MILLISECONDS.sleep(10);//等待xx毫秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return result.get(0);
    }

三、post請求

在此說明一下,后端接收的是一個name為“json”的字符串,實際就是傳了個json字符串作為請求表單中的數(shù)據(jù),后端通過解析這個json字符串進行下一步的操作

(1)同步post請求

    /**
     * 同步post請求
     * 例如:請求的最終地址為:http://127.0.0.1:8081/user/getUser/123
     * @param url 基本請求地址   例子: http://127.0.0.1:8081
     * @param json 提交的json字符串
     * @param args 請求的參數(shù)    args[]=new String[]{"user","getUser","123"}
     * @return
     */
    public static String postSyncRequest(String url,String json,String... args){
        List<String> result=new ArrayList<>();
        String address=url;
        for(int i=0;i<args.length;i++){
            address=address+"/"+args[i];
        }
        final String finalAddress = address;
        new Thread(new Runnable() {
            @Override
            public void run() {
                client=getInstance();
                Log.d("同步post請求地址:",finalAddress);
                FormBody.Builder formBody = new FormBody.Builder();
                formBody.add("json",json);
                request=new Request.Builder()
                        .url(finalAddress)
                        .post(formBody.build())
                        .addHeader("device-platform", "android")
                        .build();
                try{
                    Response response=client.newCall(request).execute();
                    String res=response.body().string();
                    result.add(res);
                    Log.d("HttpUtil", "同步post請求成功!");
                    Log.d("請求對象:", res);
                }catch (Exception e){
                    Log.d("HttpUtil", "同步post請求失敗!");
                    e.printStackTrace();
                }
            }
        }).start();
        /**因為函數(shù)返回是立刻執(zhí)行的,而result要在請求完成之后才能獲得
         * 所以需要等待result獲得返回值之后再執(zhí)行return*/
        while(result.size()==0){
            try {
                TimeUnit.MILLISECONDS.sleep(10);//等待xx毫秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return result.get(0);
    }

(2)異步post請求

    /**
     * 異步post請求
     * 例如:請求的最終地址為:http://127.0.0.1:8081/user/getUser/123
     * @param url 基本請求地址   例子: http://127.0.0.1:8081
     * @param json 提交的json字符串
     * @param args 請求的參數(shù)    args[]=new String[]{"user","getUser","123"}
     * @return
     */
    public static String postAsyncRequest(String url,String json,String... args){
        List<String> result=new ArrayList<>();
        String address=url;
        for(int i=0;i<args.length;i++){
            address=address+"/"+args[i];
        }
        final String finalAddress = address;
        Log.d("同步post請求地址:",finalAddress);
        client=getInstance();
        FormBody.Builder formBody = new FormBody.Builder();//創(chuàng)建表單請求體
        formBody.add("json",json);
        request = new Request.Builder()
                .url(finalAddress)
                .post(formBody.build())
                .addHeader("device-platform", "android")
                .build();
        Call call=client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("HttpUtil","異步post請求失??!");
                    }
                }).start();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String res = null;
                        try {
                            res = response.body().string();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        result.add(res);
                        Log.d("HttpUtil","異步post請求成功!");
                        Log.d("請求對象",res);
                    }
                }).start();
            }
        });
        /**因為函數(shù)返回是立刻執(zhí)行的,而result要在請求完成之后才能獲得
         * 所以需要等待result獲得返回值之后再執(zhí)行return*/
        while(result.size()==0){
            try {
                TimeUnit.MILLISECONDS.sleep(10);//等待xx毫秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return result.get(0);
    }

四、依賴以及相關(guān)說明

相關(guān)依賴為:(okHttp和Gson)

    implementation 'com.squareup.okhttp3:okhttp:4.2.2'
    implementation 'com.google.code.gson:gson:2.7'

由于取消掉延時會導(dǎo)致result還沒有被賦值就已經(jīng)進行到return這里了,所以在每個請求方法中在return之前都加了個延時,直到result被賦值了再執(zhí)行return

下一篇是講android是如何通過okHttp跟后端交互起來的,以及相關(guān)例子。

到此這篇關(guān)于android實現(xiàn)okHttp的get和post請求的簡單封裝與使用的文章就介紹到這了,更多相關(guān)android okHttp的get和post請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論