OkHttp-get方法
生活随笔
收集整理的這篇文章主要介紹了
OkHttp-get方法
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1.要實(shí)現(xiàn)okhttp需要添加以下依賴
implementation 'com.squareup.okhttp3:okhttp:3.4.1'2.在mainactivity.xml里面布局兩個(gè)按鈕,一個(gè)button用來請(qǐng)求發(fā)送,一個(gè)text view用來顯示我們的數(shù)據(jù)
<?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.然后對(duì)這兩個(gè)按鍵進(jìn)行綁定,將text view的實(shí)例設(shè)置為全局變量? ,下面的幾行代碼放在onCreatr()方法里面
private TextView responsetext;//設(shè)置為全局變量 Button button = findViewById(R.id.btn1);responsetext=findViewById(R.id.tv1);button.setOnClickListener(this);responsetext.setMovementMethod(ScrollingMovementMethod.getInstance());//讓textview可以下滑刷新4.在我們重寫的onclick方法里面調(diào)用get方法實(shí)現(xiàn)OK HTTP的get請(qǐng)求
@Overridepublic void onClick(View view) {if (view.getId()==R.id.btn1){get(); // post();}}5.就是我們get方法的內(nèi)容了
private void get() {new Thread(new Runnable() {//首先開啟一個(gè)新的線程@Overridepublic void run() {try {//1.創(chuàng)建一個(gè)OK HTTP client的實(shí)例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);不能在這里對(duì)主線程進(jìn)行ui更新//因?yàn)椴荒茉僮泳€程中更新ui,所以我們?cè)谶@里用runOnUiThread()方法回到主線程runOnUiThread(new Runnable() {@Overridepublic void run() {responsetext.setText(string);}});} catch (IOException e) {e.printStackTrace();}}}).start();}總結(jié)
以上是生活随笔為你收集整理的OkHttp-get方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: gitlab代码提交
- 下一篇: SAP-CDS+Odata+BOPF 创