Android 台灣中文網
標題:
OkHttp 一個支援存取HTTP的套件
[打印本頁]
作者:
ploglin
時間:
2016-3-23 09:43
標題:
OkHttp 一個支援存取HTTP的套件
開發工具:Android Studio
這是一個我常用的套件,使用起來非常的簡單、方便。主要可以用來獲取遠端的資料。
使用方式如下:
Gradle
compile "com.squareup.okhttp3:okhttp:3.2.0"
複製代碼
先介紹最簡單的作法,在主程式先加入
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
複製代碼
要調用的時候
String response = run("https://raw.github.com/square/okhttp/master/README.md");
複製代碼
這樣就可以取得遠端的資料囉,是不是還蠻方便的呢?
但如果要丟POST的話則要用另一種方法,如下
OkHttpClient client = new OkHttpClient();
public String post(String url, RequestBody body) throws IOException {
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
複製代碼
要調用的時候
RequestBody params = new FormBody.Builder()
.add("param1", "value1")
.add("param2", "value2")
.build();
String response = post("your api url", params);
複製代碼
是不是很簡單呢?供大家參考囉。
歡迎光臨 Android 台灣中文網 (https://apk.tw/)
Powered by Discuz! X3.1