java 中OkHttp的使用方法及實(shí)例
java 中OkHttp的使用方法及實(shí)例
概述
準(zhǔn)備研究Retrofit,而它是依賴OkHttp的,所以先使用一下OkHttp,不深究源碼,只探究使用方法。以后有機(jī)會(huì)再翻查源碼。
在進(jìn)行之前,首先需要2個(gè)jar包,其中一個(gè)是okHttp的jar包,github上可以下載,另一個(gè)是它的依賴包,這個(gè)很關(guān)鍵,沒有它,項(xiàng)目就無(wú)法運(yùn)行。
OkHttp請(qǐng)求的2種方式
不難猜測(cè),涉及到網(wǎng)絡(luò)請(qǐng)求,那么無(wú)非2種方式,一種是使用回調(diào),另一種則是開啟子線程執(zhí)行。
第一種:開啟子線程執(zhí)行
OkHttpClient client = new OkHttpClient();
Request build = new Request.Builder().url(url).build();
try {
<span style="white-space:pre"> </span>Response execute = client.newCall(build).execute();
if(execute.isSuccessful()){
System.out.println("wisely aaa");
} else {
System.out.println("wisely bbb");
}
} catch (IOException e) {
e.printStackTrace();
}
第二種:使用回調(diào),我個(gè)人最喜歡使用這種。(PS:覺得自己真是too young too simple??!本來(lái)以為回調(diào)的方法是在主線程,結(jié)果發(fā)現(xiàn),竟然是子線程,子線程....)
OkHttpClient client = new OkHttpClient();
Request build = new Request.Builder().url(url).build();
client.newCall(build).enqueue(new Callback() {
@Override
public void onResponse(Response arg0) throws IOException {
System.out.println("wisely success");
}
@Override
public void onFailure(Request arg0, IOException arg1) {
System.out.println("wisely failure");
}
});
OkHttp之get請(qǐng)求
1、獲取圖片
OkHttpClient client = new OkHttpClient();
Request build = new Request.Builder().url(url).build();
client.newCall(build).enqueue(new Callback() {
@Override
public void onResponse(Response response) throws IOException {
// byte[] bytes = response.body().bytes();
InputStream is = response.body().byteStream();
Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
// Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length,options);
Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
Message msg = handler.obtainMessage();
msg.obj = bitmap;
handler.sendMessage(msg);
}
@Override
public void onFailure(Request arg0, IOException arg1) {
System.out.println("wisely fail:"+arg1.getCause().getMessage());
}
});
只寫了關(guān)鍵代碼,并未寫handler的相關(guān)代碼。
獲取網(wǎng)絡(luò)圖片有2種方式,1是獲取byte數(shù)組,2是獲取輸入流。注意,onResponse在子線程中...
OkHttp之post請(qǐng)求
比起get請(qǐng)求,post請(qǐng)求的分類略多。
1、首先是最常用的表單提交。
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormEncodingBuilder()
.add("userName", "13363114390")
.add("password", "200820e3227815ed1756a6b531e7e0d2").build();
Request build = new Request.Builder().url(url).post(body).build();
client.newCall(build).enqueue(new Callback() {
@Override
public void onResponse(Response response) throws IOException {
String lenght = response.header("Content-Length");
System.out.println("wisely--lenght:" + lenght);
LoginResponse loginResponse = new Gson().fromJson(response.body().charStream(), LoginResponse.class);
System.out.println("wisely---" + loginResponse.getMessage());
}
@Override
public void onFailure(Request arg0, IOException arg1) {
System.out.println("wisely-----fail");
}
});
String tokeId;
boolean result;
public boolean isResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getTokeId() {
return tokeId;
}
public void setTokeId(String tokeId) {
this.tokeId = tokeId;
}
}
上面的是一個(gè)簡(jiǎn)單的登錄表單的提交,其中將返回的json數(shù)據(jù)封裝到了一個(gè)bean中。除了能夠獲取json數(shù)據(jù)外,還能獲取到各個(gè)消息頭。
2、上傳圖片
這是我最關(guān)心的一個(gè)功能,實(shí)驗(yàn)證明,okHttp上傳圖片的功能確實(shí)強(qiáng)大,支持多圖片上傳。
private MediaType PNG = MediaType.parse("application/octet-stream");
OkHttpClient client = new OkHttpClient();
RequestBody body = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(Headers.of("Content-Disposition","form-data; name=\"files\";filename=\"img1.jpg\""),RequestBody.create(PNG, file1))
.addPart(Headers.of("Content-Disposition","form-data; name=\"files\";filename=\"img2.jpg\""),RequestBody.create(PNG, file2)).build();
Request request = new Request.Builder()
<span style="white-space:pre"> </span>.url(url)
.post(body).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Response response) throws IOException {
if(response.isSuccessful()){
UploadPNGResponse uploadPNGResponse = new Gson().fromJson(response.body().charStream(), UploadPNGResponse.class);
String msg = uploadPNGResponse.getMsg();
List<String> list = uploadPNGResponse.getList();
for (String string : list) {
System.out.println("wisely---path:"+string);
}
}
}
@Override
public void onFailure(Request arg0, IOException arg1) {
System.out.println("wisely---fail--"+arg1.getCause().getMessage());
}
});
class UploadPNGResponse{
String msg;
boolean result;
List<String> list;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public boolean isResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
}
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
java Swing實(shí)現(xiàn)選項(xiàng)卡功能(JTabbedPane)實(shí)例代碼
這篇文章主要介紹了java Swing實(shí)現(xiàn)選項(xiàng)卡功能(JTabbedPane)實(shí)例代碼的相關(guān)資料,學(xué)習(xí)java 基礎(chǔ)的朋友可以參考下這個(gè)簡(jiǎn)單示例,需要的朋友可以參考下2016-11-11
springboot+vue實(shí)現(xiàn)Token自動(dòng)續(xù)期(雙Token方案)
雙Token方案通過(guò)訪問令牌和刷新令牌提高用戶登錄安全性和體驗(yàn),訪問令牌有效期短,包含用戶信息,用于請(qǐng)求校驗(yàn),本文就來(lái)介紹一下springboot+vue實(shí)現(xiàn)Token自動(dòng)續(xù)期(雙Token方案),感興趣的可以了解一下2024-10-10
SpringBoot使用SSE進(jìn)行實(shí)時(shí)通知前端的實(shí)現(xiàn)代碼
這篇文章主要介紹了SpringBoot使用SSE進(jìn)行實(shí)時(shí)通知前端,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-06-06
如何在java 8 stream表達(dá)式實(shí)現(xiàn)if/else邏輯
這篇文章主要介紹了如何在java 8 stream表達(dá)式實(shí)現(xiàn)if/else邏輯,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04
Maven介紹與配置+IDEA集成Maven+使用Maven命令小結(jié)
Maven是Apache軟件基金會(huì)的一個(gè)開源項(xiàng)目,是一個(gè)優(yōu)秀的項(xiàng)目構(gòu)建管理工具,它用來(lái)幫助開發(fā)者管理項(xiàng)目中的 jar,以及 jar 之間的依賴關(guān)系、完成項(xiàng)目的編譯、測(cè)試、打包和發(fā)布等工作,本文給大家介紹Maven介紹與配置+IDEA集成Maven+使用Maven命令,感興趣的朋友一起看看吧2024-01-01
java客戶端線上Apollo服務(wù)端的實(shí)現(xiàn)
這篇文章主要介紹了java客戶端線上Apollo服務(wù)端的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
java之super關(guān)鍵字用法實(shí)例解析
這篇文章主要介紹了java之super關(guān)鍵字用法實(shí)例解析,較為詳細(xì)的分析了super關(guān)鍵字的用法及內(nèi)存分布,需要的朋友可以參考下2014-09-09
java中的Arrays這個(gè)工具類你真的會(huì)用嗎(一文秒懂)
這篇文章主要介紹了java中的Arrays這個(gè)工具類你真的會(huì)用嗎,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06

