java 中OkHttp的使用方法及實例
概述
準備研究Retrofit,而它是依賴OkHttp的,所以先使用一下OkHttp,不深究源碼,只探究使用方法。以后有機會再翻查源碼。
在進行之前,首先需要2個jar包,其中一個是okHttp的jar包,github上可以下載,另一個是它的依賴包,這個很關鍵,沒有它,項目就無法運行。
OkHttp請求的2種方式
不難猜測,涉及到網絡請求,那么無非2種方式,一種是使用回調,另一種則是開啟子線程執行。
第一種:開啟子線程執行
1
2
3
4
5
6
7
8
9
10
11
12
|
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(); } |
第二種:使用回調,我個人最喜歡使用這種。(PS:覺得自己真是too young too simple!!本來以為回調的方法是在主線程,結果發現,竟然是子線程,子線程....)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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、獲取圖片
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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()); } }); |
只寫了關鍵代碼,并未寫handler的相關代碼。
獲取網絡圖片有2種方式,1是獲取byte數組,2是獲取輸入流。注意,onResponse在子線程中...
OkHttp之post請求
比起get請求,post請求的分類略多。
1、首先是最常用的表單提交。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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" ); } }); |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
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數據封裝到了一個bean中。除了能夠獲取json數據外,還能獲取到各個消息頭。
2、上傳圖片
這是我最關心的一個功能,實驗證明,okHttp上傳圖片的功能確實強大,支持多圖片上傳。
1
|
private MediaType PNG = MediaType.parse( "application/octet-stream" ); |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
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()); } }); |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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; } } |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/u013673799/article/details/49865927