欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android okhttp使用的方法

 更新時間:2021年05月06日 10:27:12   作者:qinxuexiang_blog  
本篇文章主要介紹了Android okhttp使用的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

簡介

OKHttp是一個十分常用的網(wǎng)絡(luò)請求框架了,用于android中請求網(wǎng)絡(luò)。

除了OKHttp,如今Android中主流的網(wǎng)絡(luò)請求框架有:

  • Android-Async-Http
  • Volley
  • OkHttp
  • Retrofit

依賴庫導(dǎo)入

在build.gradle 添加如下依賴

implementation 'com.squareup.okhttp3:okhttp:4.9.0'

添加網(wǎng)絡(luò)權(quán)限

<uses-permission android:name="android.permission.INTERNET"/>

get請求

/**
 *  同步Get同求
 *
 * @param url url
 * @return
 */
public String syncGet(String url) {
    String result = "";
    //1.創(chuàng)建OkHttpClient對象
    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = new Request.Builder()
            .url(url)
            .get()
            .build();
    final Call call = okHttpClient.newCall(request);
        //4.同步調(diào)用會阻塞主線程,這邊在子線程進(jìn)行
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //同步調(diào)用,返回Response,會拋出IO異常
                    Response response = call.execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();



    return result;
}

/**
 *  異步Get同求
 *
 * @param url url
 * @return
 */
public void nonSyncGet(String url, Callback responseCallback) {
    String result = null;
    //1.創(chuàng)建OkHttpClient對象
    OkHttpClient okHttpClient = new OkHttpClient();
    //2.創(chuàng)建Request對象
    Request request = new Request.Builder()
            .url(url)
            .get()
            .build();
    Call call =okHttpClient.newCall(request);
    call.enqueue(responseCallback);
}

Post請求

在OkHttp中用Post方法把鍵值對數(shù)據(jù)傳送到服務(wù)器,使用FormBody.Builder創(chuàng)建請求的參數(shù)鍵值,構(gòu)建一個RequestBody對象,

  • key-value:提交鍵值對
  • String:字符串類型
  • Form:表單數(shù)據(jù)
  • Stream:流類型
  • File:文件類型
/**
 * 同步Post同求
 *
 * @param url url
 * @return
 */
public String syncPost(String url) {
    String result = null;
    //1.創(chuàng)建OkHttpClient對象
    OkHttpClient okHttpClient = new OkHttpClient();

    FormBody.Builder mBuild = new FormBody.Builder();
    mBuild.add("name", "tony")
            .add("age", "21");
    RequestBody requestBody= mBuild.build();
    Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
    Response response = null;
    try {
        response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            result = response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return result;
}

/**
 * 異步Post同求
 *
 * @param url url
 * @return
 */
public void nonSyncPost(String url, Callback responseCallback) {
    //1.創(chuàng)建OkHttpClient對象
    OkHttpClient okHttpClient = new OkHttpClient();
    FormBody.Builder mBuild = new FormBody.Builder();
    mBuild.add("name", "tony")
            .add("age", "21");
    RequestBody requestBody= mBuild.build();
    Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
    try {
        okHttpClient.newCall(request).enqueue(responseCallback);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
/**
 * Post json
 *
 * @param url url
 * @return
 */
public String postJson(String url, Callback responseCallback) {
    String result = null;
    String jsonStr = "json";
    //1.創(chuàng)建OkHttpClient對象
    OkHttpClient okHttpClient = new OkHttpClient();
    MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
    RequestBody requestBody = RequestBody.create(mediaType, jsonStr);
    Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
    Response response = null;
    try {
        response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            result = response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return result;
}

/**
 * Post String
 *
 * @param url url
 * @return
 */
public String postString(String url, Callback responseCallback) {
    String result = null;
    //1.創(chuàng)建OkHttpClient對象
    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"),
            "{username:tony;password:123456}");
    Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
    Response response = null;
    try {
        response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            result = response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return result;
}

post表單請求

/**
 * Post 表單
 *
 * @param url url
 * @return
 */
public String postForm(String url, Callback responseCallback) {
    String result = null;
    //1.創(chuàng)建OkHttpClient對象
    OkHttpClient okHttpClient = new OkHttpClient();
    MultipartBody.Builder mBuild = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("username", "tony")
            .addFormDataPart("password", "123456");
    RequestBody requestBody= mBuild.build();
    Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
    Response response = null;
    try {
        response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            result = response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return result;
}

post 上傳文件

public void uploadFile(String url) {
    ArrayList<String> filelist = getFileList();
    //1.創(chuàng)建OkHttpClient對象
    OkHttpClient okHttpClient = new OkHttpClient();
    MultipartBody.Builder multipartBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
    for (int i = 0; i < filelist.size(); i++) {
        String path = filelist.get(i);
        File file = new File(path);
        String fileMimeType = getMimeType(file);
        //這里獲取文件類型,方法自己定義
        MediaType mediaType = MediaType.parse(fileMimeType);
        RequestBody fileBody = RequestBody.create(mediaType, file);
        multipartBody.addFormDataPart("file" + i, file.getName(), fileBody);
    }
    RequestBody requestBody = multipartBody.build();
    Request requestPostFile = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
    Response response = null;
    try {
        response = okHttpClient.newCall(requestPostFile).execute();
        if (response.isSuccessful()) {
        } else {
            throw new IOException("Unexpected code " + response);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

參考博文

https://www.jianshu.com/p/bb57bc65e4ce

https://www.jianshu.com/p/b1cf0b574e74

到此這篇關(guān)于Android okhttp使用的文章就介紹到這了,更多相關(guān)Android okhttp使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Android studio設(shè)置文件頭定制代碼注釋的方法

    Android studio設(shè)置文件頭定制代碼注釋的方法

    這篇文章主要介紹了Android studio設(shè)置文件頭定制代碼注釋的方法,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2018-08-08
  • Android ViewModel與Lifecycles和LiveData組件用法詳細(xì)講解

    Android ViewModel與Lifecycles和LiveData組件用法詳細(xì)講解

    JetPack是一個開發(fā)組件工具集,他的主要目的是幫助我們編寫出更加簡潔的代碼,并簡化我們的開發(fā)過程。JetPack中的組件有一個特點,它們大部分不依賴于任何Android系統(tǒng)版本,這意味者這些組件通常是定義在AndroidX庫當(dāng)中的,并且擁有非常好的向下兼容性
    2023-01-01
  • Android WebView 緩存詳解

    Android WebView 緩存詳解

    這篇文章主要介紹了 Android WebView 緩存詳解的相關(guān)資料,需要的朋友可以參考下
    2017-06-06
  • Android如何添加控件監(jiān)聽器(三種方式)

    Android如何添加控件監(jiān)聽器(三種方式)

    本文主要介紹了Android如何添加控件監(jiān)聽器(三種方式),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-06-06
  • 詳解Android TextView屬性ellipsize多行失效的解決思路

    詳解Android TextView屬性ellipsize多行失效的解決思路

    這篇文章主要介紹了Android TextView屬性ellipsize多行失效的解決思路,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-07-07
  • Android如何實現(xiàn)動態(tài)滾動波形圖(心電圖)功能

    Android如何實現(xiàn)動態(tài)滾動波形圖(心電圖)功能

    這篇文章主要介紹了Android如何實現(xiàn)動態(tài)滾動波形圖(心電圖)功能,幫助大家更好的理解和學(xué)習(xí)使用Android,感興趣的朋友可以了解下
    2021-03-03
  • Android自定義View實現(xiàn)支付寶咻一咻效果

    Android自定義View實現(xiàn)支付寶咻一咻效果

    這篇文章主要為大家詳細(xì)介紹了Android自定義View實現(xiàn)支付寶咻一咻效果的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-02-02
  • Android調(diào)用系統(tǒng)的發(fā)郵件功能的小例子

    Android調(diào)用系統(tǒng)的發(fā)郵件功能的小例子

    這篇文章介紹了Android調(diào)用系統(tǒng)的發(fā)郵件功能的小例子,有需要的朋友可以參考一下
    2013-08-08
  • Android?Studio實現(xiàn)彈窗設(shè)置

    Android?Studio實現(xiàn)彈窗設(shè)置

    這篇文章主要為大家詳細(xì)介紹了Android?Studio實現(xiàn)彈窗設(shè)置,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-04-04
  • Android中的存儲詳解

    Android中的存儲詳解

    大家好,本篇文章主要講的是Android中的存儲詳解,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽
    2022-01-01

最新評論