通过Android的okhttp接口访问网络接口

通过Android的okhttp接口访问网络接口

由于业务需求,需要对已发布的系统做一些功能检测,在前辈的指导下使用Android的okhttp3接口实现了工作需要,以下是代码:
项目使用springboot + gradle 布局,首先需要在build.gradel中添加依赖
implementation ‘com.squareup.okhttp3:okhttp:3.10.0’
compile group: ‘com.google.code.gson’, name: ‘gson’, version: ‘2.8.5’
其中okhttp3用来访问接口,gson用来转换json成对象

    String TOKEN = ""; 
    //创建okhttp对象
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(2, TimeUnit.MINUTES)
            .readTimeout(2, TimeUnit.MINUTES)
            .build();
            
    //创建请求体
    String bodyStr = "{\"searchvalue\":\"" + materielCode + "\"}";
    String urlStr = "接口的地址";

    RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8")
            , bodyStr);
    Request request = new Request.Builder().addHeader("Authorization", TOKEN)
            .url(urlStr)
            .post(body)
            .build();
    //创建响应体
    Response response = null;
    String responseStr = null;
    try {
        response = okHttpClient.newCall(request).execute();
        responseStr = response.body().string();

    } catch (IOException e) {
        e.printStackTrace();
    }

以上是post的请求方法;

    //创建okhttp对象
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(2, TimeUnit.MINUTES)
            .readTimeout(2, TimeUnit.MINUTES)
            .build();


    //创建请求体

    String urlStr = "" ;

    Request request = new Request.Builder().addHeader("Authorization", TOKEN)
            .url(urlStr)
            .build();

    //创建响应体
    Response response = null;
    String responseStr = null;
    try {
        response = okHttpClient.newCall(request).execute();
        responseStr = response.body().string();

    } catch (IOException e) {
        e.printStackTrace();
    }

以上是get请求对象;

         Gson gson = new Gson();
        Type materielCodeType = new TypeToken<ArrayList<Materiel>>() {
        }.getType();
        List<Materiel> materiels = (List<Materiel>) gson.fromJson(materielJsons.toString(), materielCodeType);

以上是json转对象;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值