Java通过http请求的方式调用他人的接口

本功能的实现,全部参考于这篇博客,给这位大神点赞

基于Spring Boot使用Java调用http请求的6种方式

业务背景

我在的部门的项目(官网项目)要以http请求的方式去调用别的部门(微服务项目)的接口。先来看下别的部门的http请求的参数和返回数据。如下图
在这里插入图片描述

第一步,配置url

这里http请求的url生产环境和测试环境是不同的,所以为了方便管理,这里将url的配置作为yml的配置项。

offerBuyBack:
   url: http://zuul.mircroservice-dev.10.xxx.xx.xx.nip.io/v1.0/StockService/function523

在这里插入图片描述
读取yml配置

@Value ("${offerBuyBack.url}")
private String url;

第二步,封装请求体,RequestBody

由业务背景我么可知,http的请求体Json格式如下

{
    
    
    "params":{
    
    
        "secu_code":"",
        "market":"00"
    }
}

也就是说“params”是数据头,params下又包含了多个像“market”这样的字段的参数。

我是这样理解的:这里的请求体是一个有键值对的对象,params是key,而value就是实体对象。value里又封装了各种需要传递的参数属性,像market这样的属性等....

于是我封装的value的对象就是“F523OutputVo ”这个实体类,同时也是我用来回包的VO对象

public class F523OutputVo {
    
    
    String bond_name = "";
    String last_rate = "";
    String call_rate = "";
    String market = "";
    String bond_bal_amt = "";
    
    省略set和get方法...
}

最后再将F523OutputVo 这个对象嵌套进params里

public class OfferBuyBack {
    
    

    private F523OutputVo params;

    public F523OutputVo getParams() {
    
    
        return params;
    }

    public void setParams(F523OutputVo params) {
    
    
        this.params = params;
    }
}

第三步,使用HttpURLConnection调用服务端的POST请求

截取于开头转载的博客连接

/**
  * 1.使用HttpURLConnection调用服务端的POST请求
  * 服务端入参注解: @RequestBody
  */
 public static void f1() throws Exception {
    
    
   // 1.请求URL
   String postUrl = "http://127.0.0.1:19091/server/comm/f1";
   // 2.请求参数JSON格式
   Map<String, String> map = new HashMap<>();
   map.put("userName", "HangZhou20220718");
   map.put("tradeName", "Vue进阶教程");
   String json = JSON.toJSONString(map);
   // 3.创建连接与设置连接参数
   URL urlObj = new URL(postUrl);
   HttpURLConnection httpConn = (HttpURLConnection) urlObj.openConnection();
   httpConn.setRequestMethod("POST");
   httpConn.setRequestProperty("Charset", "UTF-8");
   // POST请求且JSON数据,必须设置
   httpConn.setRequestProperty("Content-Type", "application/json");
   // 打开输出流,默认是false
   httpConn.setDoOutput(true);
   // 打开输入流,默认是true,可省略
   httpConn.setDoInput(true);
   // 4.从HttpURLConnection获取输出流和写数据
   OutputStream oStream = httpConn.getOutputStream();
   oStream.write(json.getBytes());
   oStream.flush();
   // 5.发起http调用(getInputStream触发http请求)
   if (httpConn.getResponseCode() != 200) {
    
    
       throw new Exception("调用服务端异常.");
   }
   // 6.从HttpURLConnection获取输入流和读数据
   BufferedReader br = new BufferedReader(
           new InputStreamReader(httpConn.getInputStream()));
   String resultData = br.readLine();
   System.out.println("从服务端返回结果: " + resultData);
   // 7.关闭HttpURLConnection连接
   httpConn.disconnect();
 }

————————————————
版权声明:本文为CSDN博主「zhangbeizhen18」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zhangbeizhen18/article/details/125899199

第四步,修改自己的代码

参考上面的博主的代码后,我修改的自己的代码

@Controller
@Api(tags = "报价回购 StockService服务  523 接口")
@RequestMapping("/offerBuyBack")
public class OfferBuyBackController {
    
    

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value ("${offerBuyBack.url}")
    private String url;

    @RequestMapping(value = "/getBuyBackInfo",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse offerBuyBack(@RequestBody OfferBuyBack offerBuyBack){
    
    
        List<F523OutputVo> f523OutputVos= null;

        // 1.请求URL
        String postUrl = url;
        // 2.请求参数JSON格式
        String json = null;

        try {
    
    
            json = JSON.toJSONString(offerBuyBack);

            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(json);
            //校验market的传参范围
            String market =jsonNode.findPath("market").asText();
            if(!StringUtils.isEmpty(market)){
    
    
                if(!"00".equals(market) && !"10".equals(market)){
    
    
                    throw new Exception("参数错误");
                }
            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("请求参数有误!");
        }

        HttpURLConnection httpConn = null;
        JSONArray obj = null;

        try {
    
    
            // 3.创建连接与设置连接参数
            URL urlObj = new URL(postUrl);
            httpConn = (HttpURLConnection) urlObj.openConnection();
            httpConn.setRequestMethod("POST");
            httpConn.setRequestProperty("Charset", "UTF-8");
            // POST请求且JSON数据,必须设置
            httpConn.setRequestProperty("Content-Type", "application/json");
            // 打开输出流,默认是false
            httpConn.setDoOutput(true);
            // 打开输入流,默认是true,可省略
            httpConn.setDoInput(true);
            // 4.从HttpURLConnection获取输出流和写数据
            OutputStream oStream = httpConn.getOutputStream();
            oStream.write(json.getBytes());
            oStream.flush();
            // 5.发起http调用(getInputStream触发http请求)
            if (httpConn.getResponseCode() != 200) {
    
    
                throw new Exception("调用服务端异常.");
            }
            // 6.从HttpURLConnection获取输入流和读数据
            BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
            String resultData = br.readLine();
            logger.info("从服务端返回结果: " + resultData);
            JSONObject appleJsonObject= JSONObject.parseObject(resultData);

            obj = (JSONArray) appleJsonObject.get("data");
            if(obj.size()==0){
    
    
                return ServerResponse.createByErrorMessage("微服务查询结果报错!");
            }
            //定义需要显示的Vo对象
            F523OutputVo f523OutputVo = null;
            f523OutputVos = new ArrayList<>();
            for(int i= 0;i<obj.size();i++){
    
    
                f523OutputVo =new F523OutputVo();
                f523OutputVo.setBond_name((String) obj.getJSONObject(i).get("bond_name"));
                f523OutputVo.setCall_rate((String) obj.getJSONObject(i).get("call_rate"));
                f523OutputVo.setLast_rate((String) obj.getJSONObject(i).get("last_rate"));
                f523OutputVo.setMarket((String) obj.getJSONObject(i).get("market"));
                f523OutputVo.setBond_bal_amt((String)obj.getJSONObject(i).get("bond_bal_amt"));
                f523OutputVos.add(f523OutputVo);
            }
            // 7.关闭HttpURLConnection连接
            httpConn.disconnect();
            return ServerResponse.createBySuccess("成功",f523OutputVos);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return  ServerResponse.createByErrorMessage("请求失败");
    }
}

第五步,分析请求过程

在这里插入图片描述

1.JSON.toJSONString(offerBuyBack)

在这里插入图片描述
在这里插入图片描述

2.读取json格式的数据接口,校验前端传参

在这里插入图片描述

3.创建于url的连接设置连接参数

在这里插入图片描述

4.像请求url里写请求参数

在这里插入图片描述

5.发起http调用(getInputStream触发http请求)

在这里插入图片描述

6.获取输入流读取数据

在这里插入图片描述

7.格式化返回的数据

在这里插入图片描述

8.根据需要返回的对象属性,遍历取出相应的字段

在这里插入图片描述

9.关闭HttpURLConnection连接

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/flytalei/article/details/132812760