单例 拦截器 封装ok请求

本文介绍了一种使用单例模式封装网络请求的方法,通过OkHttp库实现GET和POST请求,包括日志拦截和自定义头部信息。同时,展示了如何通过接口回调处理响应数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   //设置单例模式  拦截器   封装网络请求
public class ShowUtils {
        //设置单例

        //私有的静态的成员变量  只声明不创建
       private static ShowUtils showUtils=null;
       private static ShowUtils showUtils1;

          //私有的构造方法
    public ShowUtils() {
    }
          //返回公共静态的实例方法
     public  static  ShowUtils showUtils(){
             if (showUtils==null){
                 synchronized (ShowUtils.class){
                      if (showUtils==null){
                 showUtils1 = new ShowUtils();
                      }
                 }
             }
            return showUtils;
     }

           private static OkHttpClient okHttpClient=null;
         //返回ok
          public synchronized  static  OkHttpClient getokHttpClient(){
                  if (okHttpClient==null){
   HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                          @Override
                          public void log(String message) {
                          //*  Log.i("xxx",message);*//*
                          }
                      });
                       //创建日志拦截器模式
     httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
     
       okHttpClient =new OkHttpClient.Builder().
       //应运拦截器
       .addInterceptor(new Interceptor() {
       @Override
      public Response intercept(Chain chain) throws IOException {
        Request build = chain.request().newBuilder()
                .addHeader("source", "android")
                .build();
        return chain.proceed(build);
     }
  })
       addInterceptor(httpLoggingInterceptor)
       .build();
                  }
                  return okHttpClient;
          }

          //网络请求get方法
       public static void  doget(String url, Callback callback){
               OkHttpClient  okHttpClient = getokHttpClient();
           Request build1 = new Request.Builder().url(url).build();
           Call call = okHttpClient.newCall(build1);
                 call.enqueue(callback);
       }

     //网络请求post请求
     public void  dopost(String url, Map<String,String>mapdate, Callback callback){
         OkHttpClient  okHttpClient = getokHttpClient();
            FormBody.Builder builder = new FormBody.Builder();
                   //遍历集合
           for(String key : mapdate.keySet()){
               builder.add(key,mapdate.get(key));
           }
                 //构建
                 FormBody build1 = builder.build();

         Request build = new Request.Builder().url(url).post(build1).build();
         Call call = okHttpClient.newCall(build);
                   call.enqueue(callback);
     }

}
 //接口回调
 public interface  Show{
          //抽象方法
       void  getdate(String date);
 }
 //声明
 private Show show;
 
public void setShow(Show show) {
    this.show = show;
}

private Map<String,String> map=new HashMap<>();
map.put(“phone”, name);
map.put(“pwd”, pwd);

// src/utils/http.ts import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios' import axios from 'axios' import { getToken } from './token' import { useRouter } from 'vue-router' import { useUserStore } from '@/stores/userStores' // 定义基础响应类型 interface BaseResponse<T = any> { code: number message: string data: T ok: boolean } // 自定义配置类型 interface RequestConfig extends AxiosRequestConfig { showLoading?: boolean customError?: boolean } class Http { private instance: AxiosInstance private baseConfig: RequestConfig = { baseURL: import.meta.env.VITE_SERVE, // 从环境变量获取 timeout: 3000, headers: { 'Content-Type': 'application/json;charset=UTF-8' } } constructor() { this.instance = axios.create(this.baseConfig) this.setupInterceptors() } // 拦截器配置 private setupInterceptors() { // 请求拦截 this.instance.interceptors.request.use( (config: InternalAxiosRequestConfig) => { // 添加认证token if (getToken()) { config.headers.token = getToken() } return config }, (error) => { return Promise.reject(error) } ) // 响应拦截 this.instance.interceptors.response.use( (response: AxiosResponse) => { // 处理业务状态码 const { code, message, data } = response.data if (code === 203) { // 登录过期 ElNotification({ title: '登录过期', message: 'token过期,请重新登录', type: 'error', }) // 清除token&清除用户信息 useUserStore().logout() useRouter().replace('/login') } else if (code !== 200) { // 其他错误 ElMessage({ message: data || '请求失败', type: 'error' }) } return response }, (error) => { // 统一错误处理 // this.handleError(error) // return Promise.reject(error) console.log(error.config); new Http(error.config) } ) } // 错误处理方法 private handleError(error: any) { let message = '' if (error.response) { // 服务端返回错误 (4xx, 5xx) const { status, data } = error.response switch (status) { case 401: console.error('未授权,请重新登录') message = '未授权,请重新登录' // 跳转登录页 break case 403: console.error('拒绝访问') message = '拒绝访问' break case 404: console.error('资源不存在') message = '资源不存在' break case 500: console.error('服务器错误') message = '服务器错误' break default: console.error(`请求错误: ${status}`, data.message) message = `请求错误: ${status}` + data.message } } else if (error.request) { // 请求已发出但无响应 console.error('请求超时,请检查网络') message = '请求超时,请检查网络' } else { // 请求配置错误 console.error('请求配置错误', error.message) message = '请求配置错误' + error.message } ElMessage({ message: message, type: 'error' }) } // 通用请求方法 public request<T = any>( config: RequestConfig ): Promise<BaseResponse<T>> { return this.instance.request(config).then(res => res.data) } // GET请求 public get<T = any>( url: string, params?: object, config?: RequestConfig ): Promise<BaseResponse<T>> { return this.request({ url, method: 'GET', params, ...config }) } // POST请求 public post<T = any>( url: string, data?: object, config?: RequestConfig ): Promise<BaseResponse<T>> { return this.request({ url, method: 'POST', data, ...config }) } // PUT请求 public put<T = any>( url: string, data?: object, config?: RequestConfig ): Promise<BaseResponse<T>> { return this.request({ url, method: 'PUT', data, ...config }) } // DELETE请求 public delete<T = any>( url: string, params?: object, config?: RequestConfig ): Promise<BaseResponse<T>> { return this.request({ url, method: 'DELETE', params, ...config }) } } // 导出 export default new Http() 这是我二次封装的axios请求 把我添加一个请求失败后重新请求的方法,重新请求没有限制只要请求失败就重新发送,把添加的代码高亮出来
最新发布
07-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值