springboot -RestTemplate 发送请求

看这个学的

https://www.bilibili.com/video/BV1Zf4y1U7p5?from=search&seid=9719059667753019566&spm_id_from=333.337.0.0

也可以参考下这个(几种写法)

https://blog.csdn.net/u012702547/article/details/77917939 

 

请求头的写法参考这个

https://zhuanlan.zhihu.com/p/151984334

 

配置文件可以参考这个:

https://www.jianshu.com/p/95680c1eb6e0

 

请求配置文件

 

 

 package com.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class Restemconnfig {
    @Autowired
    private RestTemplateBuilder builder;

    @Bean
    public RestTemplate restTemplate(){
        return builder.build();
    }
}

  

上面配置文件也可以这样写

@Configuration
public class Restemconnfig {
    @Bean
    @LoadBalanced   //配置负载均衡实现---Ribbon
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

}

-----------------------------------------------------------------------------Get请求发送-----------------------------------------------------------------------------

 
import org.springframework.web.client.RestTemplate;
    @Autowired
    private RestTemplate restTemplate;

@Service
@Slf4j
public class RequestUrlServer {
    private final String url=  "http://localhost:8280/tool/aaa" ;
    @Autowired
    private RestTemplate restTemplate;

    public User resQuest(){
        ResponseEntity responseEntity =restTemplate.getForEntity(url,String.  class );
        log.info(  "响应: " +responseEntity);
      
//      获取响应体
        String body = responseEntity.getBody();
        log.info(String.valueOf(body));

//      获取响应码
        int Code = responseEntity.getStatusCodeValue();
        log.info(String.valueOf(Code));

//      获取请求头
        HttpHeaders Headers = responseEntity.getHeaders();
        log.info(String.valueOf(Headers));
       return null ; 
}

  

  • getForEntity第二个参数String.class表示我希望返回的body类型是String

 

拼接url 发送请求

private final String url = "http://localhost:8280/tool/{id}";
1
2
3
4
5
6
<code>public Map resQuest() {
        Map map2=new HashMap();
        map2.put("id","aaa");
//      发送请求
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class,map2);
</code>

 

-----------------------------------------------------------------------------Post请求发送-----------------------------------------------------------------------------

---data的话也是这么传的 亲测ok
map2= "uuu=123" 
 @Service
@Slf4j
public class RequestUrlServer {
    private final String url =  "http://localhost:8380/tool/aaa" ;
    @Autowired
    private RestTemplate restTemplate;

    public Map resQuest() {
      //请求参数
        Map map2= new HashMap();
        map2.put( "name" , "aaa" );
//      发送请求
        ResponseEntity responseEntity = restTemplate.postForEntity(url,map2,String. class );

 

 

------------------------------------------------------------------------返回值处理方法---------------------------------------------------

 //        //第一种取值方法
//        JSONObject jsonObject = JSONObject.parseObject(body);
//        log.info("响应体: " + body);
//        log.info("响应体: " + jsonObject);
//        log.info("响应体: " + jsonObject.get("name"));
//
//        //第二种取值方法
//        Map<string, string=""> map = JSONObject.<map<string, string="">>parseObject(body, Map.class);
//        log.info("响应体1: " + map);
//
////      第三种映射到类里面
//        User user = JSONObject.parseObject(body, User.class);
//        log.info(user.toString());


方法分别 返回类型 Map or User
其中User是根据返回的json 来定义
如响应返回 { "name" : "张三" }

User类为
import lombok.Data;

@Data
public class User {
    private String name;
}
</map<string,></string,>

  

---------------------------------------------------------------------带上headers请求头 请求的 方法------------------------------------------------------------

    • 希望复用 HttpHeaders
    • headers.add 方式添加请求头;而不是前面的 set方式

 

 public class RequestUrlServer {
    private final String url =  "http://localhost:8380/tool/bbb" ;
    private final String url2 =  "http://localhost:8380/tool/aaa" ;
    @Autowired
    private RestTemplate restTemplate;

    public int resQuest() {
        HttpHeaders headers =  new HttpHeaders();
        headers.set( "user-agent" ,
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36" );
        headers.set( "cookie" ,  "my_user_id=haha123; UN=1231923;gr_user_id=welcome_yhh;" );

//        请求bady参数
        Map map2= new HashMap();
        map2.put( "name" , "aaa" );

//        发送post请求带上heard
        String response = restTemplate.postForObject(url2,  new HttpEntity<>(map2, headers), String. class );
        log.info( "post with selfDefine header: {}" , response);

       
        //发送Get请求带上heard
        ResponseEntity response2 = restTemplate.exchange(url, HttpMethod.GET,  new HttpEntity<>( null , headers),String. class );
        log.info( "get with selfDefine header: {}" , response2);

 

------------------------------------------------------------统一加上请求头的写法------------------------------------------------------------

参考: https://zhuanlan.zhihu.com/p/151984334

    public int resQuest() {

        // 借助拦截器的方式来实现塞统一的请求头
        ClientHttpRequestInterceptor interceptor = (httpRequest, bytes, execution) -> {
            httpRequest.getHeaders().set( "user-agent" ,
                    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36" );
            httpRequest.getHeaders().set( "cookie" ,  "my_user_id=haha123; UN=1231923;gr_user_id=interceptor;" );
            return execution.execute(httpRequest, bytes);
        };

//        统一加入请求头
        restTemplate.getInterceptors().add(interceptor);

//        请求bady参数
        Map map2= new HashMap();
        map2.put( "name" , "aaa" );
//        发送post请求带上heard
        String response2 = restTemplate.postForObject(url2,map2,String. class );
        log.info( "post with selfDefine header: {}" , response2);

//        get请求
        String response = restTemplate.getForObject(url, String. class );
        log.info( "get with selfDefine header by Interceptor: {}" , response);

 

-------------------------------------------------------------------接口接收请求头的写法-------------------------------------------------------------------

 @PostMapping ( "/aaa" )
    public User delete_User3 ( @RequestBody User user, HttpServletRequest HttpServletRequest) {
        log.info(String.valueOf(user));
        log.info(HttpServletRequest.getHeader( "cookie" ));
        return user;
    }

 

 

 

-----------------------------------------------------------------配置文件 参数---------------------------------

 import org.apache.http.client.HttpClient;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {
   
    /**
     * http连接管理器
     * @return
     */
    @Bean
    public HttpClientConnectionManager poolingHttpClientConnectionManager() {
        /*// 注册http和https请求
        Registry registry = RegistryBuilder.create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();
        PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(registry);*/
       
        PoolingHttpClientConnectionManager poolingHttpClientConnectionManager =  new PoolingHttpClientConnectionManager();
        // 最大连接数
        poolingHttpClientConnectionManager.setMaxTotal( 500 );
        // 同路由并发数(每个主机的并发)
        poolingHttpClientConnectionManager.setDefaultMaxPerRoute( 100 );
        return poolingHttpClientConnectionManager;
    }
   
    /**
     * HttpClient
     * @param poolingHttpClientConnectionManager
     * @return
     */
    @Bean
    public HttpClient httpClient(HttpClientConnectionManager poolingHttpClientConnectionManager) {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // 设置http连接管理器
        httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);
       
        /*// 设置重试次数
        httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(3, true));*/
       
        // 设置默认请求头
        /*List
headers = new ArrayList<>(); headers.add(new BasicHeader("Connection", "Keep-Alive")); httpClientBuilder.setDefaultHeaders(headers);*/ return httpClientBuilder.build(); } /** * 请求连接池配置 * @param httpClient * @return */ @Bean public ClientHttpRequestFactory clientHttpRequestFactory(HttpClient httpClient) { HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(); // httpClient创建器 clientHttpRequestFactory.setHttpClient(httpClient); // 连接超时时间/毫秒(连接上服务器(握手成功)的时间,超出抛出connect timeout) clientHttpRequestFactory.setConnectTimeout( 5 * 1000 ); // 数据读取超时时间(socketTimeout)/毫秒(务器返回数据(response)的时间,超过抛出read timeout) clientHttpRequestFactory.setReadTimeout( 10 * 1000 ); // 连接池获取请求连接的超时时间,不宜过长,必须设置/毫秒(超时间未拿到可用连接,会抛出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool) clientHttpRequestFactory.setConnectionRequestTimeout( 10 * 1000 ); return clientHttpRequestFactory; } /** * rest模板 * @return */ @Bean public RestTemplate restTemplate(ClientHttpRequestFactory clientHttpRequestFactory) { // boot中可使用RestTemplateBuilder.build创建 RestTemplate restTemplate = new RestTemplate(); // 配置请求工厂 restTemplate.setRequestFactory(clientHttpRequestFactory); return restTemplate; } }

 

 

接口接收请求的看这儿

https://www.cnblogs.com/kaibindirver/p/15524830.html

 

 

 

 

后记:

操作响应的json----    com.alibaba.fastjson   用的是这个库


    com.alibaba
    fastjson
    1.2.47

  

 

 

 发送请求
        JSONObject response = restTemplate.postForObject(url2,  new HttpEntity<>(data, headers), JSONObject. class );
        log.info( "响应: " + response);
        String s = response.getString( "code" );
        System. out .println(s);

 

如果是返回String类型  (长得像json的string)

 String response = restTemplate.postForObject(url2,  new HttpEntity<>(map2, headers), String. class );

JSONObject  object = JSON.parseObject(response);

  

获取json 键对应的数组

JSONArray jsonArray = data2.getJSONArray("logs");

获取数组里面对应的 json

for (int i=0;i<jsonArray.size();i++){
  获取数组里面对应的 json
  HashMap aa= (HashMap) jsonArray.get(i);
获取json里面对应键的值
  String tager= (String) aa.get("content");

------------------------------------判断字符类型用上  lucaxdata.getClass().getName()

 

13、string转json格式,获取里面得到 数组或json格式的值

String targe2="{'aaa':11111,'bbb':[1,2,3,4,5,6]}";

string转json格式
JSONObject object = JSON.parseObject(targe2);;

获取json里面的aaaa的值

String object2 = targe2.getString("aaa");

如果哦aaa的值还是json

JSONObject object2 = targe2.getJSONObject("aaa");

获取json里面的数组

JSONArray object2 = targe2.getJSONArray("bbb");

 

 

 

 

 

这个不错,可以参考处理请求响应回来的json
https://www.runoob.com/w3cnote/java-json-instro.html 

https://www.cnblogs.com/chushujin/p/11371450.html

 

 

 

后记:

响应是非200请求会抛异常,可以用try去捕获

见 https://www.cnblogs.com/kaibindirver/p/15948384.html

 

 

传参数为from表单,用下面方法发送

 MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
        paramMap.add("secToken", "FuVYdeF1");
        paramMap.add("LogStoreName", "production-education");
        paramMap.add("ProjectName", "kuebernetes-production");
        //      发送请求
        JSONObject retul = restTemplate.postForObject(url2, new HttpEntity<>(paramMap, headers), JSONObject.class);
        System.out.println(retul);

 

 

 

  

 

posted @ 2021-10-12 17:31  凯宾斯基  阅读(1012)  评论(3编辑  收藏  举报