Android 台灣中文網

標題: OkHttp 一個支援存取HTTP的套件 [打印本頁]

作者: ploglin    時間: 2016-3-23 09:43
標題: OkHttp 一個支援存取HTTP的套件
開發工具:Android Studio

這是一個我常用的套件,使用起來非常的簡單、方便。主要可以用來獲取遠端的資料。

使用方式如下:

Gradle
  1. compile "com.squareup.okhttp3:okhttp:3.2.0"
複製代碼


先介紹最簡單的作法,在主程式先加入

  1.   OkHttpClient client = new OkHttpClient();
  2.   String run(String url) throws IOException {
  3.     Request request = new Request.Builder()
  4.         .url(url)
  5.         .build();
  6.     Response response = client.newCall(request).execute();
  7.     return response.body().string();
  8.   }
複製代碼


要調用的時候

  1.   String response = run("https://raw.github.com/square/okhttp/master/README.md");
複製代碼


這樣就可以取得遠端的資料囉,是不是還蠻方便的呢?

但如果要丟POST的話則要用另一種方法,如下

  1.   OkHttpClient client = new OkHttpClient();
  2.   public String post(String url, RequestBody body) throws IOException {
  3.     Request request = new Request.Builder()
  4.         .url(url)
  5.         .post(body)
  6.         .build();
  7.     Response response = client.newCall(request).execute();
  8.     return response.body().string();
  9.   }
複製代碼

要調用的時候

  1.   RequestBody params = new FormBody.Builder()
  2.         .add("param1", "value1")
  3.         .add("param2", "value2")
  4.         .build();
  5.   String response = post("your api url", params);
複製代碼


是不是很簡單呢?供大家參考囉。




歡迎光臨 Android 台灣中文網 (https://apk.tw/) Powered by Discuz! X3.1