RestTemplate请求

package com.istrong.guarantee.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.client.RestTemplate;


/**
 * @program: sm_guarantee_platform
 * @ClassName AppConfig
 * @description:注册bean、系统配置注解开启
 * @author: 黄涛
 * @create: 2025-01-10 16:03
 * @Version 1.0
 **/
@Configuration
public class AppConfig {

    /**
     * 注册restTemplate的bean
     * @return
     */
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
    
}
package com.istrong.guarantee.component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: sm_guarantee_platform
 * @ClassName ThirdPartyService
 * @description:HTTP访问的模板类
 * @author: 黄涛
 * @create: 2025-01-10 15:41
 * @Version 1.0
 **/
@Component
public final class RestTemplateService {

    private final RestTemplate restTemplate;
    public RestTemplateService(RestTemplate restTemplate){
        this.restTemplate = restTemplate;
    }


    /**
     * post,application/json
     * @param url
     * @param param
     * @return
     */
    public final Map post(String url, Map<String, Object> param) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(param, headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        return JSONObject.parseObject(response.getBody());
    }


    /**
     * get,application/x-www-form-urlencoded
     * @param url
     * @return
     */
    public final Map get(String url) {
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        return JSONObject.parseObject(response.getBody());
    }


    /**
     * get,application/x-www-form-urlencoded
     * @param url
     * @param map
     * @return
     */
    public final Map get(String url,Map<String,String> map) {
        url += "?" + map.entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue()).collect(Collectors.joining("&"));
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        Map ret_map = JSON.parseObject(responseEntity.getBody());
        return ret_map;
    }
}

 

posted on 2025-01-24 11:49  五官一体即忢  阅读(9)  评论(0)    收藏  举报

导航