java 中OkHttp的使用方法及實例
創(chuàng)新互聯(lián)公司主要從事成都做網(wǎng)站、網(wǎng)站制作、網(wǎng)頁設(shè)計、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)麻江,十多年網(wǎng)站建設(shè)經(jīng)驗,價格優(yōu)惠、服務(wù)專業(yè),歡迎來電咨詢建站服務(wù):18982081108
概述
準(zhǔn)備研究Retrofit,而它是依賴OkHttp的,所以先使用一下OkHttp,不深究源碼,只探究使用方法。以后有機會再翻查源碼。
在進(jìn)行之前,首先需要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 > </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 > </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; } }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
文章標(biāo)題:java 中OkHttp的使用方法及實例
網(wǎng)頁鏈接:http://chinadenli.net/article48/joijep.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供搜索引擎優(yōu)化、網(wǎng)站設(shè)計、App設(shè)計、外貿(mào)建站、、微信公眾號
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)