首頁 > Java > java教程 > 主體

java 中OkHttp的使用方法及實例詳解

怪我咯
發布: 2017-07-02 10:29:31
原創
2059 人瀏覽過

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

java  中OkHttp的使用方法及實例

概述

準備研究Retrofit,而它是依賴OkHttp的,所以先使用OkHttp,不深究源碼,只探究使用方法。以後有機會再翻查源碼。

在進行之前,首先需要2個jar包,其中一個是okHttp的jar包,github上可以下載,另一個是它的依賴包,這個很關鍵,沒有它,專案就無法運作。

OkHttp請求的2種方式

#都不難猜測,涉及到網路請求,那麼無非2種方式,一種是使用回調,另一種則是開啟子執行緒執行。

第一種:開啟子執行緒執行

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!!本來以為回呼的方法是在主線程,結果發現,竟然是子線程,子線程....)

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()); 
  } 
});
登入後複製

只寫了關鍵程式碼,並未寫handler的相關代碼。

取得網路圖片有2種方式,1是取得byte陣列,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資料封裝到了一個bean中。除了能夠取得json資料外,還能取得到各個訊息標頭。

2、上傳圖片

這是我最關心的功能,實驗證明,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; 
  } 
}
登入後複製

以上是java 中OkHttp的使用方法及實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!