java 中OkHttp的使用方法及實例
java 中OkHttp的使用方法及實例
概述
準備研究Retrofit,而它是依賴OkHttp的,所以先使用一下OkHttp,不深究源碼,只探究使用方法。以后有機會再翻查源碼。
在進行之前,首先需要2個jar包,其中一個是okHttp的jar包,github上可以下載,另一個是它的依賴包,這個很關(guān)鍵,沒有它,項目就無法運行。
OkHttp請求的2種方式
不難猜測,涉及到網(wǎng)絡(luò)請求,那么無非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),我個人最喜歡使用這種。(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請求
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請求
比起get請求,post請求的分類略多。
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; } }
上面的是一個簡單的登錄表單的提交,其中將返回的json數(shù)據(jù)封裝到了一個bean中。除了能夠獲取json數(shù)據(jù)外,還能獲取到各個消息頭。
2、上傳圖片
這是我最關(guān)心的一個功能,實驗證明,okHttp上傳圖片的功能確實強大,支持多圖片上傳。
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; } }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
Spring @Value如何通過${}、#{}注入不同類型的值
這篇文章主要介紹了Spring @Value如何通過${}、#{}注入不同類型的值問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05利用Spring Data MongoDB持久化文檔數(shù)據(jù)的方法教程
這篇文章主要給大家介紹了關(guān)于利用Spring Data MongoDB持久化文檔數(shù)據(jù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考借鑒,下面來一起看看吧。2017-08-08Mybatis-Plus使用saveOrUpdate及問題解決方法
本文主要介紹了Mybatis-Plus使用saveOrUpdate及問題解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-01-01SpringBoot @PostMapping接收HTTP請求的流數(shù)據(jù)問題
這篇文章主要介紹了SpringBoot @PostMapping接收HTTP請求的流數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02SpringBoot + openFeign實現(xiàn)遠程接口調(diào)用的過程
現(xiàn)在的微服務(wù)項目不少都使用的是springboot+spring cloud構(gòu)建的項目,微服務(wù)之間的調(diào)用都離不開feign來進行遠程調(diào)用,這篇文章主要介紹了SpringBoot + openFeign實現(xiàn)遠程接口調(diào)用,需要的朋友可以參考下2022-11-11Springboot集成Springbrick實現(xiàn)動態(tài)插件的步驟詳解
這篇文章主要介紹了Springboot集成Springbrick實現(xiàn)動態(tài)插件的詳細過程,文中的流程通過代碼示例介紹的非常詳細,感興趣的同學可以參考一下2023-06-06