iT邦幫忙

2021 iThome 鐵人賽

DAY 7
0
Mobile Development

android studio 30天學習筆記系列 第 7

android studio 30天學習筆記-day 7-介紹okhttp

  • 分享至 

  • xImage
  •  

okhttp是常用的第三方庫,跟retrofit、Volley一樣都能做網絡連線的請求。
今天就做個簡單的okhttp實作。
網址:https://jsonplaceholder.typicode.com/posts

加入dependencies

    implementation 'com.squareup.okhttp3:okhttp:4.7.2'

在androidManifest.xml添加權限

    <uses-permission android:name="android.permission.INTERNET" />

okHttpClient:建立客戶端類

private OkHttpClient okHttpClient =new OkHttpClient().newBuilder()
//   .connectTimeout(5, TimeUnit.SECONDS). //設置Timeout連線時間
    build();

Request:設置連線資訊

 Request request =new Request.Builder()
                .url("https://jsonplaceholder.typicode.com/posts/3")//連結的網址
                .build();

Call:回傳資訊

Call call=okHttpClient.newCall(request);
        //異步執行
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("OkHttp result:", e.getMessage());

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("OkHttp response:", response.body().string());

            }
        });
    }

完整code

public class MainActivity extends AppCompatActivity {
       
    private OkHttpClient okHttpClient =new OkHttpClient().newBuilder()
            
            .build();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }
    //GetResponeClick監聽事件:將api用get方法取回
    public void GetResponeClick(View view) {
        Request request =new Request.Builder()
                .url("https://jsonplaceholder.typicode.com/posts/3")
              //.addHeader("","")  //如果API有需要header,可使用addHeader發送
                .build();
        Call call=okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("OkHttp result:", e.getMessage());

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("OkHttp response:", response.body().string());

            }
        });
    }
    //PostResponsClick監聽事件:將api用post方法送出
    public void PostResponsClick(View view) {
        FormBody formBody=new FormBody.Builder() //FormBody設置要傳的值
                .add("UserId","101")
                .add("id","101" )
                .add("title","Hello Everyone")
                .add("body","Nice to see you")
                .build();
        Request request =new Request.Builder()
                .url("https://jsonplaceholder.typicode.com/posts")
                .post(formBody) //將formBody寫入
                .build();
        Call call =okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("OkHttp result:", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                Log.d("OkHttp response:", response.body().string());

            }
        });
    }
}

get回傳
https://ithelp.ithome.com.tw/upload/images/20210713/2013896646V7YV5mxX.png
post回傳
https://ithelp.ithome.com.tw/upload/images/20210713/20138966ag65nP2Pgs.png

HttpLoggingInterceptor
檢查api傳輸情況的套件,非常好用
首先加入dependencies

    implementation 'com.squareup.okhttp3:logging-interceptor:4.7.2'

要用的話在OkHttpClient加入addInterceptor

private OkHttpClient okHttpClient =new OkHttpClient().newBuilder()
            .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
            .build();

搜尋okhttp就可以看到Log了
https://ithelp.ithome.com.tw/upload/images/20210713/20138966ScwwQW0qTP.png


上一篇
android studio 30天學習筆記-day 6-介紹retrofit(二)
下一篇
android studio 30天學習筆記-day 8-基本介紹rxjava2
系列文
android studio 30天學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言