病历系统-通过http请求访问外部接口

   由于本项目医生信息和病历信息需要访问his系统数据,自己项目不会保存相关信息所以需要经常调用外部接口,现打算使用httpclient来解决。

Spring 中如何使用Rest资源

借助 RestTemplate,Spring应用能够方便地使用REST资源 
Spring的 RestTemplate访问使用了模版方法的设计模式.

模版方法将过程中与特定实现相关的部分委托给接口,而这个接口的不同实现定义了接口的不同行为。

主要用到以下方法

getForEntity() 发送一个HTTP GET请求,返回的ResponseEntity包含了响应体所映射成的对象

getForObject() 发送一个HTTP GET请求,返回的请求体将映射为一个对象

postForEntity() POST 数据到一个URL,返回包含一个对象的ResponseEntity,这个对象是从响应体中映射得 
到的

postForObject() POST 数据到一个URL,返回根据响应体匹配形成的对象
 

  1. 第一步导入相关jar包
<properties>
   <httpclient.version>4.5.5</httpclient.version>
</properties>
<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
   <version>${httpclient.version}</version>
</dependency>

  2. 在service下添加,restTemplate已经再在方法调用后自动关闭流

@Service
public class HttpClient {

    @Bean
    public RestTemplate getRestTemplate(){
        RestTemplate restTemplate = new RestTemplate();
        //解决中文乱码
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }

    /**
     *  发送get、post请求
     * @param url       请求地址
     * @param method    请求方法
     * @param params    请求参数
     * @return
     */
    public Result client(String url, HttpMethod method, MultiValueMap<String,String> params){
        RestTemplate template = new RestTemplate();
        ResponseEntity<Result> responseEntity = null;
        if (method.matches("GET")){
            responseEntity = template.getForEntity(url, Result.class,params);
            System.out.println("进入get请求");
        } else {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
            responseEntity = template.postForEntity(url, request, Result.class);
            System.out.println("进入post请求");
        }
        return responseEntity.getBody();
    }

}

  3. 写接口

@RestController
public class SysLoginController {

   @Autowired
   private HttpClient httpClient;

  
   @RequestMapping("/hello")
   public Result hello(){
      String url = "http://127.0.0.1:8081/api/xxxxx";
      HttpMethod method = HttpMethod.POST;
      MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
      params.add("test","2");
      Result result = httpClient.client(url, method, params);
      System.out.println(result);
      return result;

   }

   
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值