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)目就無法運(yùn)行。
OkHttp請(qǐng)求的2種方式
不難猜測(cè),涉及到網(wǎng)絡(luò)請(qǐng)求,那么無非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!!本來以為回調(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)文章
Spring @Value如何通過${}、#{}注入不同類型的值
這篇文章主要介紹了Spring @Value如何通過${}、#{}注入不同類型的值問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05java實(shí)現(xiàn)釘釘機(jī)器人消息推送的示例代碼
這篇文章主要介紹了java實(shí)現(xiàn)釘釘機(jī)器人消息推送的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01利用Spring Data MongoDB持久化文檔數(shù)據(jù)的方法教程
這篇文章主要給大家介紹了關(guān)于利用Spring Data MongoDB持久化文檔數(shù)據(jù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考借鑒,下面來一起看看吧。2017-08-08Mybatis-Plus使用saveOrUpdate及問題解決方法
本文主要介紹了Mybatis-Plus使用saveOrUpdate及問題解決方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01SpringBoot @PostMapping接收HTTP請(qǐng)求的流數(shù)據(jù)問題
這篇文章主要介紹了SpringBoot @PostMapping接收HTTP請(qǐng)求的流數(shù)據(jù)問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02Java Netty實(shí)現(xiàn)心跳機(jī)制過程解析
這篇文章主要介紹了Java Netty實(shí)現(xiàn)心跳機(jī)制過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03SpringBoot + openFeign實(shí)現(xiàn)遠(yuǎn)程接口調(diào)用的過程
現(xiàn)在的微服務(wù)項(xiàng)目不少都使用的是springboot+spring cloud構(gòu)建的項(xiàng)目,微服務(wù)之間的調(diào)用都離不開feign來進(jìn)行遠(yuǎn)程調(diào)用,這篇文章主要介紹了SpringBoot + openFeign實(shí)現(xiàn)遠(yuǎn)程接口調(diào)用,需要的朋友可以參考下2022-11-11Springboot集成Springbrick實(shí)現(xiàn)動(dòng)態(tài)插件的步驟詳解
這篇文章主要介紹了Springboot集成Springbrick實(shí)現(xiàn)動(dòng)態(tài)插件的詳細(xì)過程,文中的流程通過代碼示例介紹的非常詳細(xì),感興趣的同學(xué)可以參考一下2023-06-06