OkHttp是用於網路連線的第三方套件,其連線效率高,還能夠取消連線和快取等機制,相較於一般常見的連線方式,程式碼更為簡潔。
gradle:
//okhttp
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
//好用的攔截器
implementation 'com.squareup.okhttp3:logging-interceptor:4.9.1'
註記:版本需一樣
權限:
<uses-permission android:name="android.permission.INTERNET" />
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
.build();
Request request = new Request.Builder()
.url("https://jsonplaceholder.typicode.com/posts/1")
.build();
GET
GET
//okHttpClient加入request
Call call = okHttpClient.newCall(request);
//執行
call.enqueue(new Callback() {
@Override
//失敗
public void onFailure(Call call, IOException e) {
Log.d("result",e.getMessage());
}
@Override
//成功
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
//若需執行UI工作,則需要runOnUiThread
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,"get",Toast.LENGTH_SHORT).show();
textView.setText(result);
Log.d("result",result);
}
});
}
});
以上就是okhttp的使用方法拉,希望各位能先對okhttp有個認識,預告一下,他在之後的文章還會出現喔~