iT邦幫忙

2022 iThome 鐵人賽

DAY 13
0
Mobile Development

Android Studio 30天學習紀錄系列 第 13

Android Studio 30天學習紀錄-Day13 okhttp

  • 分享至 

  • xImage
  •  

今天主要來應用okhttp的這個套件,與Retrofit、HttpUrlConnection等雷同,都是可進行連線取回資料並解析,執行取傳值的動作,那麼今天主要要透過假資料網站來做,那麼就開始介紹,首先先添加需要的權限以及依賴。

權限

因為會用到網路,所以添加網路的權限至Manifest中。

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

依賴

將okhttp需要的依賴加入至gradle中。

implementation 'com.squareup.okhttp3:okhttp:4.7.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.7.0'
implementation 'com.squareup.okhttp3:okhttp-urlconnection:4.7.0'

UI

https://ithelp.ithome.com.tw/upload/images/20220924/20139259SInsjUJQsV.jpg


OkHttp

透過使用Okhttp進行連線至少會使用到以下三個物件:

  • OkhttpClient(建置連線基底、可加Timeout及攔截器Interceptor等)
private OkHttpClient okHttpClient =new OkHttpClient().newBuilder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30,TimeUnit.SECONDS)
            .readTimeout(30,TimeUnit.SECONDS)
            .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
            .build();

  • Request(建置連線資訊,資訊包含get post方法、header、要連的url等)
Request request = new Request.Builder()
    .url("https://jsonplaceholder.typicode.com/posts/1")
    .addHeader("Content-Type","application/json")
    .get()
    .build();

  • Call(執行連線,並取得http回傳)
 Call call=okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onResponse(Call call, Response response){
            //連線成功,取得回傳response
        }
        @Override
        public void onFailure(Call call, IOException e) {
            //當連線失敗
        }
    });

程式

那麼接著來設計程式,今天主要加入了兩顆按鈕,一顆用來做POST而另一顆做GET,這兩個差最多在Request資料的建置上,post需要多寫入一個json body的資料,而最後將這兩個結果進行Log來顯示。

public class MainActivity extends AppCompatActivity {
    //建立連線基底,並加入Interceptor(攔截器)
    private OkHttpClient okHttpClient =new OkHttpClient().newBuilder()
            .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC)).build();
    private TextView txv;
    private Button btn_get,btn_post;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txv=findViewById(R.id.textView);
        btn_get=findViewById(R.id.btn_get);
        btn_post=findViewById(R.id.btn_post);
        btn_get.setOnClickListener(view->{
            //連線資訊建立
            Request request = new Request.Builder()
                    .url("https://jsonplaceholder.typicode.com/posts/1")
                    .build();
            //call執行request
            Call call=okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onResponse(Call call, Response response){
                    try {
                        String result = response.body().string();
                        Log.d("Response",""+result);
                    } catch (Exception e) {
                        Log.d("Error",""+e);
                    }
                }
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.d("OkHttp Error:", e.getMessage());

                }
            });
        });
        btn_post.setOnClickListener(view->{
            FormBody formBody=new FormBody.Builder() //FormBody設置(用來post的資料
                    .add("UserId","101")
                    .add("id","101" )
                    .add("title","this is title")
                    .add("body","this is body")
                    .build();
            Request request =new Request.Builder()
                    .url("https://jsonplaceholder.typicode.com/posts")
                    .post(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){
                    try {
                        String result = response.body().string();
                        Log.d("Response",""+result);
                    } catch (Exception e) {
                        Log.d("Error",""+e);
                    }
                }
            });
        });
    }
}

成果

https://ithelp.ithome.com.tw/upload/images/20220924/20139259B1OnX8owYe.jpg


上一篇
Android Studio 30天學習紀錄-Day12 Scope
下一篇
Android Studio 30天學習紀錄-Day14 DataBinding雙向綁定
系列文
Android Studio 30天學習紀錄30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言