美文网首页
springboot 支持httpclient 26

springboot 支持httpclient 26

作者: 张力的程序园 | 来源:发表于2020-04-16 10:51 被阅读0次

一个服务访问另外一个服务的技术有很多种,比如feign, dubbo, activemq, ajax+jsonp等,httpclient是其中之一。本节讲述如何在springboot中使用httpclient。

1、环境约束

  • win10 64位操作系统
  • idea2018.1.5
  • maven-3.0.5
  • jdk-8u162-windows-x64

2、前提约束

3、操作步骤

  • 加入依赖:
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
        </dependency>
  • 在主启动类同级目录下创建HttpClientConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class HttpClientConfig{

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
    }
}
  • 在主启动类同级目录下创建UserController.java
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;
@Controller
public class UserController{

    @Resource
    RestTemplate restTemplate;

    @RequestMapping("/query")
    @ResponseBody
    public String queryUser()
    {
        String apiurl = "http://localhost:8080/query";//假设这个api可以查询出用户
        ResponseEntity<Map> forEntity = restTemplate.getForEntity(apiurl , Map.class);
        return "ok";
    }
}

以上就是springboot中使用httpclient的过程。

相关文章

网友评论

      本文标题:springboot 支持httpclient 26

      本文链接:https://www.haomeiwen.com/subject/saglvhtx.html