Android okhttp使用的方法
簡介
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è)置文件頭定制代碼注釋的方法,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-08-08Android ViewModel與Lifecycles和LiveData組件用法詳細(xì)講解
JetPack是一個開發(fā)組件工具集,他的主要目的是幫助我們編寫出更加簡潔的代碼,并簡化我們的開發(fā)過程。JetPack中的組件有一個特點,它們大部分不依賴于任何Android系統(tǒng)版本,這意味者這些組件通常是定義在AndroidX庫當(dāng)中的,并且擁有非常好的向下兼容性2023-01-01詳解Android TextView屬性ellipsize多行失效的解決思路
這篇文章主要介紹了Android TextView屬性ellipsize多行失效的解決思路,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07Android如何實現(xiàn)動態(tài)滾動波形圖(心電圖)功能
這篇文章主要介紹了Android如何實現(xiàn)動態(tài)滾動波形圖(心電圖)功能,幫助大家更好的理解和學(xué)習(xí)使用Android,感興趣的朋友可以了解下2021-03-03Android自定義View實現(xiàn)支付寶咻一咻效果
這篇文章主要為大家詳細(xì)介紹了Android自定義View實現(xiàn)支付寶咻一咻效果的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-02-02Android調(diào)用系統(tǒng)的發(fā)郵件功能的小例子
這篇文章介紹了Android調(diào)用系統(tǒng)的發(fā)郵件功能的小例子,有需要的朋友可以參考一下2013-08-08Android?Studio實現(xiàn)彈窗設(shè)置
這篇文章主要為大家詳細(xì)介紹了Android?Studio實現(xiàn)彈窗設(shè)置,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-04-04