OkHttp-get方法
生活随笔
收集整理的這篇文章主要介紹了
OkHttp-get方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.要實現okhttp需要添加以下依賴
implementation 'com.squareup.okhttp3:okhttp:3.4.1'2.在mainactivity.xml里面布局兩個按鈕,一個button用來請求發送,一個text view用來顯示我們的數據
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"><Buttonandroid:id="@+id/btn1"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="SEND" /><ScrollViewandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"><LinearLayoutandroid:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"><TextViewandroid:id="@+id/tv1"android:layout_width="match_parent"android:layout_height="match_parent"/></LinearLayout></ScrollView></LinearLayout >3.然后對這兩個按鍵進行綁定,將text view的實例設置為全局變量? ,下面的幾行代碼放在onCreatr()方法里面
private TextView responsetext;//設置為全局變量 Button button = findViewById(R.id.btn1);responsetext=findViewById(R.id.tv1);button.setOnClickListener(this);responsetext.setMovementMethod(ScrollingMovementMethod.getInstance());//讓textview可以下滑刷新4.在我們重寫的onclick方法里面調用get方法實現OK HTTP的get請求
@Overridepublic void onClick(View view) {if (view.getId()==R.id.btn1){get(); // post();}}5.就是我們get方法的內容了
private void get() {new Thread(new Runnable() {//首先開啟一個新的線程@Overridepublic void run() {try {//1.創建一個OK HTTP client的實例OkHttpClient client = new OkHttpClient();Request builder = new Request.Builder().url("https://www.qq.com").get().build();Response response = client.newCall(builder).execute();String string = response.body().string();Log.i("TAG", "run: 0"+string); // responsetext.setText(string);不能在這里對主線程進行ui更新//因為不能再子線程中更新ui,所以我們在這里用runOnUiThread()方法回到主線程runOnUiThread(new Runnable() {@Overridepublic void run() {responsetext.setText(string);}});} catch (IOException e) {e.printStackTrace();}}}).start();}總結
以上是生活随笔為你收集整理的OkHttp-get方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: gitlab代码提交
- 下一篇: SAP-CDS+Odata+BOPF 创