JAvaにおけるOkHttpの使用方法及び例

6868 ワード

java  中OkHttpの使用方法及び例
概要
Retrofitを研究する準備をしていますが、OkHttpに依存しているので、まずOkHttpを使って、ソースコードを深く研究せず、使用方法だけを探究します.後でソースコードを調べる機会があります.
行う前に、まず2つのjarパッケージが必要です.そのうちの1つはokHttpのjarパッケージで、githubでダウンロードできます.もう1つは依存パッケージです.これは重要です.それがなければ、プロジェクトは実行できません.
OkHttpリクエストの2つの方式
ネットワークリクエストに関わると,コールバックを用いる方式と,サブスレッド実行を開く方式の2つにほかならない.
1つ目:サブスレッド実行をオンにする

OkHttpClient client = new OkHttpClient(); 
Request build = new Request.Builder().url(url).build(); 
try { 
  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(); 
} 

2つ目は、コールバックを使って、個人的にはこれが一番好きです.(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、写真をアップロードする
これは私の最も関心を持つ1つの機能で、実験は証明して、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() 
    .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 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 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 getList() { 
    return list; 
  } 
  public void setList(List list) { 
    this.list = list; 
  } 
} 

 読書に感謝して、みんなを助けることができることを望んで、みんなの当駅に対する支持に感謝します!