通过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>() {
        }.getType();
        List materiels = (List) gson.fromJson(materielJsons.toString(), materielCodeType);

以上是json转对象;

你可能感兴趣的:(通过Android的okhttp接口访问网络接口)