完成一个get请求
1.导入依赖
implementation("com.squareup.okhttp3:okhttp:3.14.+")
2.开启viewBinding
android.buildFeatures.viewBinding = true
3.加网络权限 和 http明文请求允许配置文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"><uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/><applicationandroid:allowBackup="true"android:dataExtractionRules="@xml/data_extraction_rules"android:fullBackupContent="@xml/backup_rules"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/Theme.OkHttp"android:networkSecurityConfig="@xml/network_security_config"tools:targetApi="31"><activityandroid:name=".MainActivity"android:exported="true"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>
<?xml version="1.0" encoding="utf-8"?>
<network-security-config><base-config cleartextTrafficPermitted="true" />
</network-security-config>
4.布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity"><Buttonandroid:id="@+id/btn1"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="请求"/><TextViewandroid:id="@+id/text"android:layout_width="match_parent"android:layout_height="wrap_content"/>
</LinearLayout>
5.Activity
package com.tiger.okhttp;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;
import android.util.Log;
import android.view.View;import com.tiger.okhttp.databinding.ActivityMainBinding;import java.io.IOException;
import java.util.concurrent.TimeUnit;import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;public class MainActivity extends AppCompatActivity {ActivityMainBinding binding;OkHttpClient okHttpClient;@Overrideprotected void onCreate(Bundle savedInstanceState) {//使用ViewBindingsuper.onCreate(savedInstanceState);binding = ActivityMainBinding.inflate(getLayoutInflater());setContentView(binding.getRoot());okHttpClient = new OkHttpClient.Builder().connectTimeout(3, TimeUnit.SECONDS).build();binding.btn1.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {testGet();}});}private void testGet() {//请求方法//post表单数据写法// FormBody formBody = new FormBody.Builder()
// .add("start", "0")
// .add("count", "8")
// .build();RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"),"{\"start\":0,\"count\":8}");Request request = new Request.Builder().url("http://192.168.202.55:8999/findPost?start=0&count=8").post(requestBody).build();//同步请求
// new Thread(new Runnable() {
// @Override
// public void run() {
// try {
// Response response = okHttpClient.newCall(request).execute();
//
// ResponseBody body = response.body();
// if (body != null) {
// String s = body.string();
//
// Log.d("ning", s);
//
//
// runOnUiThread(() -> {
// binding.text.setText(s);
// });
//
// }
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
// }).start();//异步请求okHttpClient.newCall(request).enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {//失败}@Overridepublic void onResponse(Call call, Response response) throws IOException {//有相应的情况下ResponseBody body = response.body();if (body != null) {String s = body.string();Log.d("ning", s);runOnUiThread(() -> {binding.text.setText(s);});}}});}}