Android okhttp使用的方法
簡介
OKHttp是一個十分常用的網(wǎng)絡請求框架了,用于android中請求網(wǎng)絡。
除了OKHttp,如今Android中主流的網(wǎng)絡請求框架有:
- Android-Async-Http
- Volley
- OkHttp
- Retrofit
依賴庫導入
在build.gradle 添加如下依賴
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
添加網(wǎng)絡權限
<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.同步調用會阻塞主線程,這邊在子線程進行
new Thread(new Runnable() {
@Override
public void run() {
try {
//同步調用,返回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ù)傳送到服務器,使用FormBody.Builder創(chuàng)建請求的參數(shù)鍵值,構建一個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
到此這篇關于Android okhttp使用的文章就介紹到這了,更多相關Android okhttp使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Android通過XListView實現(xiàn)上拉加載下拉刷新功能
這篇文章主要為大家詳細介紹了Android通過XListView實現(xiàn)上拉加載下拉刷新功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-12-12
Android編程實現(xiàn)仿優(yōu)酷圓盤旋轉菜單效果的方法詳解【附demo源碼下載】
這篇文章主要介紹了Android編程實現(xiàn)仿優(yōu)酷圓盤旋轉菜單效果的方法,涉及Android界面布局及事件響應相關操作技巧,并附帶demo源碼供讀者下載參考,需要的朋友可以參考下2017-08-08
Android開發(fā)實現(xiàn)廣告無限循環(huán)功能示例
這篇文章主要介紹了Android開發(fā)實現(xiàn)廣告無限循環(huán)功能,結合完整實例形式分析了Android廣告圖片輪播功能的具體實現(xiàn)步驟與相關功能、布局等操作技巧,需要的朋友可以參考下2017-11-11
Android三種方式實現(xiàn)ProgressBar自定義圓形進度條
這篇文章主要介紹了Android三種方式實現(xiàn)ProgressBar自定義圓形進度條的相關資料,需要的朋友可以參考下2016-03-03
Listview加載的性能優(yōu)化是如何實現(xiàn)的
在android開發(fā)中Listview是一個很重要的組件,它以列表的形式根據(jù)數(shù)據(jù)的長自適應展示具體內(nèi)容,用戶可以自由的定義listview每一列的布局,接下來通過本文給大家介紹Listview加載的性能優(yōu)化是如何實現(xiàn)的,對listview性能優(yōu)化相關知識感興趣的朋友一起學習吧2016-01-01

