OkHttpClient如何发get请求以及post请求

一:get请求

  1. 加入依赖
<dependency>
              <groupId>com.squareup.okhttp3</groupId>
              <artifactId>okhttp</artifactId>
              <version>3.4.1</version>
        </dependency>

  1. 写代码
    2.1配置OkHttpClient
    2.2请求参数
    2.3请求头配置
public class Test{
private static OkHttpClient httpClient;
    static {
        httpClient = new OkHttpClient.Builder()
                //设置连接超时时间
                .connectTimeout(30, TimeUnit.SECONDS)
                //设置读取超时时间
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
    }
   
   //该接口假设为被对接的接口
@GetMapping("/getApplicationConfig")
    public ApplicationConfigVO getApplicationConfig(@RequestParam("type") int type){
        ApplicationConfigVO configVO = new ApplicationConfigVO();
        //pc端是type是1,移动端type2
        if (type==1){
            configVO.setApplicationId(pcApplicationId);
        }else {
            configVO.setBusinessModelId(businessModelId);
            
        }
       return configVO;
    }
     
     //这是测试接口
    @GetMapping("/test")
    public ApplicationConfigVO test(@RequestParam("type") int type, HttpServletRequest request1){
        Response response = null;
        ApplicationConfigVO configVO;
        try {
            Request request = new Request.Builder()
                     //这里必须手动设置为json内容类型
                    .addHeader("content-type", "application/json")
                    //设置token
                    .addHeader("x-auth0-token",request1.getHeader("x-auth0-token"))
                    //参数放到链接后面
                    .url("http://localhost:18008/application/getApplicationConfig?type="+type)             
                    .build();
                    //发送请求
            response = httpClient.newCall(request).execute();
            //将响应数据转换字符传(实际是json字符传)
            String respStr = response.body().string();
            //将响应数据转换json对象
            JSONObject object = JSONObject.parseObject(respStr);
            //取json对象指定数据
            JSONObject jsonObject = object.getJSONObject("data");
            //将数据转换指定的对象
             configVO = JSONObject.parseObject(JSONObject.toJSONString(jsonObject), ApplicationConfigVO.class);
        } catch (Exception e) {
            log.error("获取配置失败:{}", e.getMessage(), e);
            throw new RestException("获取配置失败:" + e.getMessage());
        } finally {
            if (null != response) {
                response.close();
            }
        }
        return configVO;
    }
}

二:post请求

  1. 加入依赖
<dependency>
              <groupId>com.squareup.okhttp3</groupId>
              <artifactId>okhttp</artifactId>
              <version>3.4.1</version>
        </dependency>

  1. 写代码
    2.1配置OkHttpClient
    2.2请求参数
    2.3请求头配置
public class Test{
private static OkHttpClient httpClient;
    static {
        httpClient = new OkHttpClient.Builder()
                //设置连接超时时间
                .connectTimeout(30, TimeUnit.SECONDS)
                //设置读取超时时间
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
    }
   
   //该接口假设为被对接的接口
@PostMapping("/getApplicationConfig")
    public ApplicationConfigVO getApplicationConfig(@RequestBody SubcategoryVO subcategoryVO, HttpServletRequest request1){
       String status = subcategoryVO.getStatus();
        int type = Integer.parseInt(status);
        ApplicationConfigVO configVO = new ApplicationConfigVO();
        //pc端是type是1,移动端type2
        if (type==1){
            configVO.setApplicationId(pcApplicationId);
        }else {
            configVO.setBusinessModelId(businessModelId);
            
        }
       return configVO;
    }

    @GetMapping("/test")
    public ApplicationConfigVO test(@RequestParam("type") int type, HttpServletRequest request1){
        Response response = null;
        ApplicationConfigVO configVO;
        try {
            //设置请求参数
            JSONObject paramObject = new JSONObject();
            paramObject.put("status", type);
            Request request = new Request.Builder()
                     //这里必须手动设置为json内容类型
                    .addHeader("content-type", "application/json")
                    //设置token
                    .addHeader("x-auth0-token",request1.getHeader("x-auth0-token"))
                    //参数放到链接后面
                    .url("http://localhost:18008/application/getApplicationConfig)             
                    .post(okhttp3.RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramObject.toString()))
                    .build();
                    //发送请求
            response = httpClient.newCall(request).execute();
            //将响应数据转换字符传(实际是json字符传)
            String respStr = response.body().string();
            //将响应数据转换json对象
            JSONObject object = JSONObject.parseObject(respStr);
            //取json对象指定数据
            JSONObject jsonObject = object.getJSONObject("data");
            //将数据转换指定的对象
             configVO = JSONObject.parseObject(JSONObject.toJSONString(jsonObject), ApplicationConfigVO.class);
        } catch (Exception e) {
            log.error("获取配置失败:{}", e.getMessage(), e);
            throw new RestException("获取配置失败:" + e.getMessage());
        } finally {
            if (null != response) {
                response.close();
            }
        }
        return configVO;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值