日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

OkHttp-get方法

發布時間:2023/12/29 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。