创建Network公共类 (这里面都没有加token,如果需要可以自行添加)
添加依赖
implementation 'com.squareup.okhttp3:okhttp:4.9.3' implementation 'com.google.code.gson:gson:2.8.9'
添加网络权限 AndroidManifest.xml里面添加
<uses-permission android:name="android.permission.INTERNET" />
在application里面添加
android:usesCleartextTraffic="true"
package com.example.myapplication;import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.widget.ImageView;import androidx.annotation.NonNull;import org.jetbrains.annotations.NotNull;import java.io.IOException;
import java.io.InputStream;
import java.security.PublicKey;
import java.util.function.BiFunction;import javax.xml.transform.OutputKeys;import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;public class NetWork {private static OkHttpClient client=new OkHttpClient.Builder().build();//get请求方式public static void get(String url, Callback callback){Request request=new Request.Builder().url(url).build();client.newCall(request).enqueue(callback);}//post请求方式public static void post(String url,Callback callback,String token,String json){RequestBody body=RequestBody.create(MediaType.get(""),json);Request request=new Request.Builder().url(url).post(body).build();client.newCall(request).enqueue(callback);}//网络图片下载public static void getimg(String url, ImageView img) throws IOException {img.setTag(url);Request request=new Request.Builder().url(url).build();Response response=client.newCall(request).execute();Bitmap bitmap= BitmapFactory.decodeStream(response.body().byteStream());//判断图片是否重复显示img.post(new Runnable() {public void run() {if (url.equals(img.getTag())) {img.setImageBitmap(bitmap);}}});}}