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

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)文章

最新評論