Android网络请求篇

OkHttp工具类

	//首先要导入依赖
	implementation 'com.squareup.okhttp3:okhttp:3.12.1'
	//okhttp
	
	public class OKHttpUtil {
    //3、提供一个本地OKHttpUtil引用
    private static OKHttpUtil okHttpUtil;
    private final OkHttpClient okHttpClient;

    //单例模式
    //1、私有化构造函数
    //作用:不能被其他外部内容访问
    private OKHttpUtil() {
        //创建OKHttp对象
        okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new RedirectInterceptor())
                .addInterceptor(new LogInterceptor())
                .build();
    }

    //2、提供公有方法供外部类访问
    public static OKHttpUtil getInstance() {
        //DCL模式的懒汉式
        if (null == okHttpUtil) {
            synchronized (OKHttpUtil.class) {
                if (null == okHttpUtil) {
                    okHttpUtil = new OKHttpUtil();
                }
            }
        }
        return okHttpUtil;
    }

    public void post(RequestBody requestBody,String urlString,Callback callback) {
        //①在这里首先需要请求体,但是需要具体类进行提供,所以把RequestBody作为参数进行传入
        //②然后需要请求地址参数,也需要具体类进行提供,所以也把URL作为参数进行传入
        Request request = new Request.Builder()
                .method("POST", requestBody)
                .url(urlString)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(callback);
    }

    public void get(String urlString,Callback callback){
        //所需的参数是URL地址
        Request request = new Request.Builder()
                .url(urlString)
                .build();
        okHttpClient.newCall(request).enqueue(callback);
    }

	}	

以上是单例模式封装的Okhttp工具类,下面给大家在分享一个当前流行的一个网络请求以及给大家推荐一个更加简洁的网络请求工具

Retiofit(当前流行)

定义base接口(封装URL地址和数据请求)

//常量类中,存放请求地址
public class Constant {
// 原始地址
// "http://m2.qiushibaike.com/article/list/latest?page=1";
//根地址,进行地址拆分,必须以/结尾

public static final String BASE_URL = "http://m2.qiushibaike.com/";

//维度电商请求http://mobile.bwstudent.com/small/user/v1/login
//根地址

public static final String MALL_BASE_URL = "http://mobile.bwstudent.com/";
}

子接口存放的内容

public interface ApiService {

@GET("article/list/latest?")
Call<ResponseBody> getResponseDataWithQueryMapInfo(@QueryMap Map<String, String> map);

@GET("article/list/{Alex}?")
Call<ResponseBody> getResponseDataWithQueryMapInfoUpdatePath(@Path("Alex") String path, @QueryMap Map<String, String> map);

@FormUrlEncoded
@POST("small/user/v1/login")
Call<ResponseBody> postResponseDataWithQueryInfo(@Field("phone") String phone, @Field("pwd") String pwd);
}

**Activity或Fragment中进行使用

	//拼接根地址
    //可以获取到根地址
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constant.BASE_URL)
            .build();
    //3.通过Retrofit实例创建接口服务对象
    //+子地址
    ApiService service = retrofit.create(ApiService.class);
    //4.接口服务对象调用接口中的方法,获取Call对象
    Call<ResponseBody> call = service.getResponseData();
    //5.Call对象执行请求(异步、同步请求)
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            try {
                ResponseBody responseBody = response.body();
                //响应数据
                String responseData = responseBody.string();
                tvContent.setText(responseData);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            String errorMessage = t.getMessage();
            tvContent.setText(errorMessage);
        }
    });

OKgo(简单方便)

//导依赖
implementation 'com.lzy.net:okgo:3.0.4'
	//okgo
	OkGo.<String>get(Constant.SHOPPING_URL).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
            	//成功的回调
            }

OKgo慎用!由于是三方封装好的框架,对于信息安全方面肯定不如自己处理,如有需要请二次封装!!!

拦截器工具类

public class LogInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        //请求之前
        //打印系统时间
        Log.d("LogInterceptor", "System.nanoTime():" + System.nanoTime());
        //打印头部信息
        Headers headers = request.headers();
        String type = headers.get("content-type");
        String cache = headers.get("cache-control");
        Log.d("LogInterceptor", type + "……" + cache);
        //请求之后
        Response response = chain.proceed(request);
        //打印系统时间
        Log.d("LogInterceptor", "System.nanoTime():" + System.nanoTime());
        return response;
    }
	}

创作不易,仅供参考,如有问题,评论留言,如有雷同,纯属巧合!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值