springboot 支持httpclient 26

2020-04-16  本文已影响0人  张力的程序园

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

1、环境约束

2、前提约束

3、操作步骤

        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
        </dependency>
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());
    }
}
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的过程。

上一篇 下一篇

猜你喜欢

热点阅读