一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - java 中OkHttp的使用方法及實例

java 中OkHttp的使用方法及實例

2020-11-18 10:43Java教程網 Java教程

這篇文章主要介紹了java 中OkHttp的使用方法及實例的相關資料,需要的朋友可以參考下

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

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 特级毛片全部免费播放器 | 亚洲色图丝袜 | 亚洲国产剧情中文视频在线 | 2022av小四郎的最新地址 | 99热碰 | 韩国美女被的免费视频 | 欧美日韩国产另类一区二区三区 | 色综合久久日韩国产 | 精品午夜寂寞影院在线观看 | 黄瓜视频免费 | 成人久久网站 | 星空无限传媒xk8046 | 韩国日本香港毛片免费 | 日本阿v精品视频在线观看 日本xxx片免费高清在线 | 天天干女人 | 日本一卡二卡3卡四卡网站精品 | 久久强奷乱码老熟女 | 91精品国产高清久久久久久 | 短篇同学新婚h系列小说 | 91精品综合国产在线观看 | 国产视频一区二区 | 久久久GOGO无码啪啪艺术 | 欧美1| 经典千人斩一区二区视频 | 四虎免费看黄 | 国偷盗摄自产福利一区在线 | 91制片厂免费观看 | 日韩操片| 久久一本岛在免费线观看2020 | 紧身裙女教师波多野结衣 | 性色AV一区二区三区V视界影院 | 国产一页 | 动漫jk美女被爆羞羞漫画 | 忘忧草在线社区WWW日本直播 | 被强上后我成瘾了小说 | 精品国偷自产在线 | 99免费精品 | 男女拍拍拍免费视频网站 | 国产精品最新 | 俄罗斯美女破苞 | 97色资源 |