Http调用
http调用即通过http方式调用第三方接口,现成的工具库有很多,如HttpClient、RestTemplate、OKHttp,今天主要介绍Hutool-http
前置环境
Spring Initializr初始化项目 选择Spring Web和Lombok依赖 Java版本1.8
application.yml配置如下:
server: servlet: context-path: /api port: 8123
引入Hutool依赖:
<dependency> <groupId>cn.hutoolgroupId> <artifactId>hutool-allartifactId> <version>5.8.15version> dependency>
先写一个简单的被调用接口
主要功能就是:
- GET调用返回名字
- POST调用返回名字
- POST调用返回User对象
Controller
package com.zd.zdinterface.controller;import com.zd.zdinterface.model.User;import org.springframework.web.bind.annotation.*;@RestController@RequestMapping("/name")public class NameController { @GetMapping("/") public String getNameByGet(String name) { return "GET 你的名字是:" + name; } @PostMapping("/") public String getNameByPost(@RequestParam String name) { return "Post 你的名字是:" + name; } @PostMapping("/user") public String getUserNameByPost(@RequestBody User user) { return user.getUsername(); }}
User:
package com.zd.zdinterface.model;import lombok.Data;@Datapublic class User { private String username;}
开始调用
先写一个简单的Client类
Client:
package com.zd.zdinterface.client;import cn.hutool.http.HttpRequest;import cn.hutool.http.HttpResponse;import cn.hutool.http.HttpUtil;import cn.hutool.json.JSONUtil;import com.zd.zdinterface.model.User;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestParam;import java.util.HashMap;public class ZdApiClient { //调用接口方法一 public String getNameByGet(String name) { HashMap paramMap = new HashMap<>(); paramMap.put("name", name); String result3= HttpUtil.get("http://localhost:8123/api/name/", paramMap); System.out.println(result3); return result3; } //调用接口方法二 public String getNameByPost(@RequestParam String name) { HashMap paramMap = new HashMap<>(); paramMap.put("name", name); String result3= HttpUtil.post("http://localhost:8123/api/name/", paramMap); System.out.println(result3); return result3; } //调用接口方法三 public String getUserNameByPost(@RequestBody User user) { String json = JSONUtil.toJsonStr(user); HttpResponse httpResponse = HttpRequest.post("http://localhost:8123/api/name/user") .body(json) .execute(); System.out.println(httpResponse.getStatus()); String result = httpResponse.body(); System.out.println(result); return result; }}
为什么这样写?需要看官方文档:
其中包括安装
以及使用
测试
package com.zd.zdinterface;import com.zd.zdinterface.client.ZdApiClient;import com.zd.zdinterface.model.User;public class Main { public static void main(String[] args) { ZdApiClient zdApiClient = new ZdApiClient(); String res1 = zdApiClient.getNameByGet("zd"); String res2 = zdApiClient.getNameByPost("zd"); User user = new User(); user.setUsername("zd"); String res3 = zdApiClient.getUserNameByPost(user); System.out.println(res1); System.out.println(res2); System.out.println(res3); }}
结果
来源地址:https://blog.csdn.net/qq_39411709/article/details/129641909