How OkHttpClient sends get request and post request

One: get request

  1. Add dependencies
<dependency>
              <groupId>com.squareup.okhttp3</groupId>
              <artifactId>okhttp</artifactId>
              <version>3.4.1</version>
        </dependency>

  1. Writing code
    2.1 Configuring OkHttpClient
    2.2 Request parameters
    2.3 Request header configuration
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;
    }
}

Two: post request

  1. Add dependencies
<dependency>
              <groupId>com.squareup.okhttp3</groupId>
              <artifactId>okhttp</artifactId>
              <version>3.4.1</version>
        </dependency>

  1. Writing code
    2.1 Configuring OkHttpClient
    2.2 Request parameters
    2.3 Request header configuration
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;
    }
}

Guess you like

Origin blog.csdn.net/linyiwwy/article/details/128208767