SpringBoot发起http请求,RestTemplate.exchange携带请求头,携带参数

配置超时时间

package com.rjgf.sso.other.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;


/**
 * @author 
 * @date 2022/10/14 9:58
 * @remark RestTemplate配置
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        //1000ms*15 15s
        factory.setReadTimeout(1000*15);
        factory.setConnectTimeout(1000*15);
        return factory;
    }
}

自动注入
依赖包

	@Autowired
    private RestTemplate restTemplate;
    
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.*;

1.POST请求

package com.rjgf.common.core.utils.rest;

import com.alibaba.fastjson.JSONObject;
import com.rjgf.common.core.constant.HttpStatus;
import com.rjgf.common.core.exception.base.BaseException;
import com.rjgf.common.core.web.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

/**
 * @author 
 * @date 2022/10/26 16:49
 * @remark
 */
@Component
public class RestInnerServerUtils {

    private static final Logger log = LoggerFactory.getLogger(RestInnerServerUtils.class);

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 发起rest请求
     *
     * @param url    路径
     * @param params 请求参数
     * @return URL
     */
    public Object post(String url, JSONObject params) {
        //请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
         //发起请求 String代表发送的类型,这里使用jsonStr,网上很多博客一个抄一个,用LinkedMultiValueMap、MultiValueMap作为参数传递,现在绝大数项目用json格式,接受会导致参数错误
        HttpEntity<String> httpEntity = new HttpEntity<>(params.toJSONString(), headers);
         //AjaxResult是返回类型,我知道返回类型,如果不确定返回类型,使用String接受,用fastjson处理Json字符串
        ResponseEntity<AjaxResult> responseEntity = restTemplate.exchange(
                url,
                HttpMethod.POST,
                httpEntity,
                AjaxResult.class);
        return getObject(responseEntity);
    }

    /**
     * 发起rest请求
     *
     * @param url 路径
     * @return URL
     */
    public Object get(String url) {
        //请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        //将参数和请求头放入实体 参数用jsonStr
        HttpEntity<String> httpEntity = new HttpEntity<>(null, headers);
        ResponseEntity<AjaxResult> responseEntity = restTemplate.exchange(
                url,
                HttpMethod.GET,
                httpEntity,
                AjaxResult.class);
        return getObject(responseEntity);
    }

    private Object getObject(ResponseEntity<AjaxResult> responseEntity) {
        if (!responseEntity.getStatusCode().is2xxSuccessful()) {
            log.info("验证服务器状态码不为200");
            throw new BaseException("获取token失败");
        }
        AjaxResult ajax = responseEntity.getBody();
        if (ObjectUtils.isEmpty(ajax)) {
            throw new BaseException("响应体不能为空");
        }
        if (HttpStatus.SUCCESS != (int) ajax.get(AjaxResult.CODE_TAG)) {
            throw new BaseException((String) ajax.get(AjaxResult.MSG_TAG));
        }
        return ajax.get(AjaxResult.DATA_TAG);
    }
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,可以使用RestTemplate类来发送HTTP请求RestTemplateSpring框架提供的一个用于访问Rest服务的客户端工具。它提供了多种方法来发送不同类型的HTTP请求,包括GET、POST、PUT、DELETE等。 要使用RestTemplate发送POST请求,可以使用其中的exchange方法。exchange方法可以发送任意类型的HTTP请求,并且可以接收响应结果。 下面是使用RestTemplate发送POST请求的示例代码: ```java import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; public class RestClient { public static void main(String[] args) { // 创建RestTemplate对象 RestTemplate restTemplate = new RestTemplate(); // 设置请求头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); // 设置请求参数 MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("param1", "value1"); params.add("param2", "value2"); // 创建HttpEntity对象,包含请求头和请求参数 HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers); // 发送POST请求 ResponseEntity<String> responseEntity = restTemplate.exchange("http://example.com/api", HttpMethod.POST, requestEntity, String.class); // 获取响应结果 String response = responseEntity.getBody(); System.out.println(response); } } ``` 在上面的示例代码中,我们首先创建了一个RestTemplate对象。然后,我们设置了请求头和请求参数,并创建了一个HttpEntity对象来包含这些信息。最后,我们使用exchange方法发送POST请求,并通过ResponseEntity对象获取响应结果。 需要注意的是,上述示例中的URL和参数仅作为示例,实际使用时需要根据具体的接口和参数进行修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值